package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.InfoFeeType;
import com.ybkj.daijia.OrderNumberConfig;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.chart.TableOrderMonthVo;
import com.ybkj.daijia.common.CompanyOrderVo;
import com.ybkj.daijia.common.DriverOrderDetailVo;
import com.ybkj.daijia.common.DriverOrderVo;
import com.ybkj.daijia.common.MemberOrderVo;
import com.ybkj.daijia.common.OrderFromSourceVo;
import com.ybkj.daijia.common.PageVo;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.config.ZhuanxianApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.OrderRevokeTimerTask;
import com.ybkj.daijia.server.amqp.PushMessage;
import com.ybkj.daijia.server.event.common.event.IntroduceRebateEvent;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.MemberConsumedEvent;
import com.ybkj.daijia.server.event.model.zhuanxian.ZhuanxianOrderCallBackEvent;
import com.ybkj.daijia.server.event.model.zhuanxian.ZhuanxianOrderCancelEvent;
import com.ybkj.daijia.server.event.model.zhuanxian.ZhuanxianOrderFinishEvent;
import com.ybkj.daijia.server.event.model.zhuanxian.ZhuanxianOrderPaidanEvent;
import com.ybkj.daijia.server.mapper.AdminRoleMapper;
import com.ybkj.daijia.server.mapper.AreaMapper;
import com.ybkj.daijia.server.mapper.CompanyMapper;
import com.ybkj.daijia.server.mapper.DriverChoseLevelCarMapper;
import com.ybkj.daijia.server.mapper.DriverChoseLevelZhuanxianMapper;
import com.ybkj.daijia.server.mapper.DriverLevelDetailMapper;
import com.ybkj.daijia.server.mapper.DriverLevelMapper;
import com.ybkj.daijia.server.mapper.DriverLevelMoneyTimeDetailMapper;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.mapper.DriverPaymentsRecordMapper;
import com.ybkj.daijia.server.mapper.FinancialRecordMapper;
import com.ybkj.daijia.server.mapper.FirstOrderPassengerMapper;
import com.ybkj.daijia.server.mapper.RoleAuthorityMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.mc.PassengerAddress;
import com.ybkj.daijia.server.model.AdminRole;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.ChartDay;
import com.ybkj.daijia.server.model.ChartMonth;
import com.ybkj.daijia.server.model.ChartYear;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverChoseLevelZhuanxian;
import com.ybkj.daijia.server.model.DriverLevel;
import com.ybkj.daijia.server.model.DriverLevel.TimePoint;
import com.ybkj.daijia.server.model.DriverLevelDetail;
import com.ybkj.daijia.server.model.DriverLevelDetail.DriverLevelType;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail;
import com.ybkj.daijia.server.model.DriverLevelMoneyDetail.DriverLevelMoneyType;
import com.ybkj.daijia.server.model.DriverLevelMoneyTimeDetail;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.FinancialRecord;
import com.ybkj.daijia.server.model.FirstOrderPassenger;
import com.ybkj.daijia.server.model.HelpPayRecord;
import com.ybkj.daijia.server.model.Rate;
import com.ybkj.daijia.server.model.RoleAuthority;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Activity.OrderType;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.DriverHelppayService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.zhuanxian.Car;
import com.ybkj.daijia.server.zhuanxian.Line;
import com.ybkj.daijia.server.zhuanxian.Order;
import com.ybkj.daijia.server.zhuanxian.Order.PayTypeDetails;
import com.ybkj.daijia.server.zhuanxian.OrderMemo;
import com.ybkj.daijia.server.zhuanxian.OrderOrbit;
import com.ybkj.daijia.server.zhuanxian.OrderReview;
import com.ybkj.daijia.server.zhuanxian.OrderStatus;
import com.ybkj.daijia.server.zhuanxian.PayRecordOrder;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;

@Service
public class DefaultZhuanxianService implements ZhuanxianService {
    private static final Logger logger = LoggerFactory.getLogger(DefaultZhuanxianService.class);
    @Autowired
    private ZhuanxianApi zhuanxianApi;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private DriverService driverService;
    @Autowired
    private PassengerApi passengerApi;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private FinancialRecordMapper financialRecordMapper;

    @Autowired
    private DriverPaymentsRecordMapper driverPaymentsRecordMapper;
    @Autowired
    private DriverChoseLevelCarMapper driverChoseLevelCarMapper;
    @Autowired
    private DriverLevelDetailMapper driverLevelDetailMapper;
    @Autowired
    private DriverLevelMoneyTimeDetailMapper driverLevelMoneyTimeDetailMapper;
    @Autowired
    private SmsService smsService;
    @Autowired
    private DriverLevelMapper driverLevelMapper;
    @Autowired
    private DriverChoseLevelZhuanxianMapper driverChoseLevelZhuanxianMapper;
    @Autowired
    private FirstOrderPassengerMapper firstOrderPassengerMapper;
    @Autowired
    private DriverHelppayService helppayService;
    @Autowired
    private SalesApi salesApi;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private RoleAuthorityMapper roleAuthorityMapper;

    @Override
    public List<Line> queryLines(Long companyId) {
        List<Line> list = new ArrayList<Line>();

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_LINE_PARAM)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (companyId != null && companyId != 0) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(result)) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Long total = data.getLong("total");
                JSONArray rows = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(rows.toString(), new TypeToken<List<Line>>() {
                }.getType());
                if (list != null && list.size() != 0) {
                    for (Line line : list) {
                        Area area = areaMapper.selectByPrimaryKey(line.getAreaId());
                        line.setArea(area);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public Page<Map> queryCarsByParams(Long companyId, String companyName, String lineName,
        String carNumber, String employName, String allstatus) {
        Subject subject = SecurityUtils.getSubject();
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_CAR_PARAM)
            .append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", String.valueOf(companyName));
            builder.append("&companyName={companyName}");
        }
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(lineName)) {
            kv.put("lineName", String.valueOf(lineName));
            builder.append("&lineName={lineName}");
        }
        if (StringUtils.isNotBlank(carNumber)) {
            kv.put("carNumber", carNumber);
            builder.append("&carNumber={carNumber}");
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.put("employName", employName);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(allstatus)) {
            kv.put("statuss", String.valueOf(allstatus));
            builder.append("&statuss={statuss}");
        }
        List<Car> list = new ArrayList<Car>();
        long total = 0;
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                //储存需要显示的车辆下标
                List<Integer> carsIndex = new ArrayList<>();
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject car = ja.getJSONObject(i);
                    JSONArray lines = null;
                    Object obj = car.get("lines");
                    if (null != obj && !"null".equals(obj.toString())) {
                        //获取车辆绑定线路
                        lines = car.getJSONArray("lines");
                    }

                    if (null != lines) {
                        //是否存在线路权限
                        boolean exsits = false;
                        //遍历线路,判断该车辆是否拥有该当前角色所绑定的线路
                        for (int l = 0; l < lines.length(); l++) {
                            JSONObject line = lines.getJSONObject(l);
                            if (subject.isPermitted(line.get("id").toString())) {
                                exsits = true;
                                break;
                            }
                        }
                        //如果没有线路，保存起来，不显示该车辆信息
                        if (!exsits) {
                            carsIndex.add(i);
                        }
                    }

                }
                //对arraylist进行降序排序，解决arraylist通过下标remove的下标越界异常
                if (carsIndex.size() > 0) {
                    Collections.sort(carsIndex, new Comparator<Integer>() {
                        @Override
                        public int compare(Integer o1, Integer o2) {
                            return o2 - o1;
                        }
                    });
                    for (Integer index : carsIndex) {
                        ja.remove(index);
                    }
                }
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        //存放权限
        List<String> authority = new ArrayList<>();
        if (subject.isPermitted("deleteZXVehicle")) {
            authority.add("deleteZXVehicle");
        }
        if (subject.isPermitted("editZXVehicle")) {
            authority.add("editZXVehicle");
        }
        List<Map> resultList = new ArrayList<>();
        Map<String, List> map = new HashMap<>();
        map.put("authority", authority);
        map.put("cars", list);
        resultList.add(map);
        return new PageImpl<Map>(resultList, pageable, total);
    }

    @Override
    public Map<String, Object> createCar(Long companyId, String companyName, String carName,
        String carNumber, Long[] lineId,
        Long employId, String employName,
        Integer ridepeopleNumber) throws ParseException {
        Map<String, Object> carMap = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("carName", carName);
        kv.add("carNumber", carNumber);
        StringBuilder lineStr = new StringBuilder();
        for (int i = 0; i < lineId.length; i++) {
            lineStr.append(lineId[i]);
            if (i != lineId.length - 1) {
                lineStr.append(",");
            }
        }
        System.out.println(lineStr);
        kv.add("lineId", lineStr.toString());
        kv.add("ridepeopleNumber", String.valueOf(ridepeopleNumber));

        if (employId != null && employId != 0) {
            kv.add("employId", String.valueOf(employId));
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.add("employName", employName);
        }
        String result = zhuanxianApi
            .post(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.CREATE_CAR, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            Car car = gson.fromJson(data.toString(), Car.class);
            if (car != null && employId != null) {
                Driver driver = driverMapper.selectByPrimaryKey(employId);
                if (driver != null) {
                    driver.setZhuanxianCarId(car.getId());
                    driverMapper.updateByPrimaryKey(driver);
                }
            }
            carMap.put("message", "创建成功");
            carMap.put("success", true);
        } else {
            carMap.put("message", jo.getString("message"));
            carMap.put("success", false);
        }

        return carMap;
    }

    @Override
    public Car findCar(Long id) {
        return zhuanxianApi.findOneCar(id, settingUtils.get()).getResult();
    }

    @Override
    public Map<String, Object> updateCar(Long carId, Long companyId, String companyName,
        String carName,
        String carNumber, Long[] lineId, Integer status, Long employId,
        String employName, Integer ridepeopleNumber) {

        Map<String, Object> map = new HashMap<String, Object>();
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.UPDATE_ZHUANXIAN_CAR)
            .append("?carId={carId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carId", String.valueOf(carId));
        if (companyId != null && companyId != 0) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        if (StringUtils.isNotBlank(companyName)) {
            builder.append("&companyName={companyName}");
            kv.put("companyName", companyName);
        }
        if (StringUtils.isNotBlank(carName)) {
            builder.append("&carName={carName}");
            kv.put("carName", carName);
        }
        if (StringUtils.isNotBlank(carNumber)) {
            builder.append("&carNumber={carNumber}");
            kv.put("carNumber", carNumber);
        }
        if (lineId != null && lineId.length != 0) {
            builder.append("&lineId={lineId}");
            StringBuilder sb = new StringBuilder();
            int leng = lineId.length;
            for (int i = 0; i < leng; i++) {
                sb.append(lineId[i]);
                if (i < leng - 1) {
                    sb.append(",");
                }
            }
            kv.put("lineId", sb.toString());
        }
        if (status != null) {
            builder.append("&status={status}");
            kv.put("status", String.valueOf(status));
        }
        if (ridepeopleNumber != null) {
            builder.append("&ridepeopleNumber={ridepeopleNumber}");
            kv.put("ridepeopleNumber", String.valueOf(ridepeopleNumber));
        }
        if (StringUtils.isBlank(employName)) {
            employId = null;
        }
        if (employId != null) {
            kv.put("employId", String.valueOf(employId));
            builder.append("&employId={employId}");
        }
        if (StringUtils.isNotBlank(employName)) {
            kv.put("employName", employName);
            builder.append("&employName={employName}");
        }

        String result = null;
        try {
            if (employId != null) {
                Driver driver = driverMapper.selectByPrimaryKey(employId);//新指派的员工
                if (driver != null) {
                    if (driver.getZhuanxianCarId() != null && carId != driver
                        .getZhuanxianCarId()) {//车辆id和新指派员工上面的车辆id不相同(强行指派)
                        Long carid = driver.getCarId();
                        driver.setZhuanxianCarId(carId);
                        driverMapper.updateByPrimaryKey(driver);
                        Driver driver2 = driverMapper.selectByZhuanxianCarId(carid);//旧服务人员
                        if (driver2 != null) {
                            driver2.setZhuanxianCarId(null);
                            driverMapper.updateByPrimaryKey(driver2);
                        }
                    } else if (driver.getZhuanxianCarId() == null) {//新员工的车辆id为空(正常指派)
                        Driver driver2 = driverMapper.selectByZhuanxianCarId(carId);
                        if (driver2 != null) {
                            driver2.setZhuanxianCarId(null);
                            driverMapper.updateByPrimaryKey(driver2);
                        }
                        driver.setZhuanxianCarId(carId);
                        driverMapper.updateByPrimaryKey(driver);
                    }
                }

            } else {
                driverMapper.deleteZhuanxianCarRelation(carId);
            }

            result = zhuanxianApi.post(builder.toString(), kv, settingUtils.get());
            if (StringUtils.isBlank(result)) {
                map.put("success", false);
                map.put("message", "修改失败");
            } else {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    map.put("success", true);
                    map.put("message", "修改成功");
                } else {
                    map.put("success", false);
                    map.put("message", jo.getString("message"));
                }

            }

        } catch (HttpClientErrorException e) {
            result = e.getResponseBodyAsString();
        } catch (HttpServerErrorException e) {
            result = e.getResponseBodyAsString();
        }
        return map;
    }

    @Override
    public Page<Line> queryByLineCompany(Long companyId, String companyName) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_LINE_PARAM)
            .append("?appKey={appKey}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", String.valueOf(companyName));
            builder.append("&companyName={companyName}");
        }
        if (companyId != null) {
            kv.put("companyId", String.valueOf(companyId));
            builder.append("&companyId={companyId}");
        }
        List<Line> list = new ArrayList<Line>();
        long total = 0;
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Line>>() {
                }.getType());
                for (Line line : list) {
                    line.setArea(areaMapper.selectByPrimaryKey(line.getAreaId()));
                    line.setBaocheArea(areaMapper.selectByPrimaryKey(line.getBaocheAreaId()));
                    line.setJihuoArea(areaMapper.selectByPrimaryKey(line.getJihuoAreaId()));
                }
            }
        }
        return new PageImpl<Line>(list, pageable, total);
    }

    @Override
    public Map<String, Object> createLine(Long companyId, String companyName, String name,
        String startCity, String startAddress, String endCity,
        String endAddress, Long areaId, Long jihuoAreaId, Long baocheAreaId, String contactNumber,
        Long[] roleId) {
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("name", name);
        kv.add("startCity", startCity);
        kv.add("startAddress", startAddress);
        kv.add("endCity", endCity);
        kv.add("endAddress", endAddress);
        kv.add("areaId", String.valueOf(areaId));
        kv.add("baocheAreaId", String.valueOf(baocheAreaId));
        kv.add("jihuoAreaId", String.valueOf(jihuoAreaId));
        kv.add("contactNumber", contactNumber);

        String result = zhuanxianApi
            .post(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.CREATE_LINE, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            Line line = new Line();
            line = gson.fromJson(data.toString(), Line.class);
            if (roleId.length > 0) {
                for (int i = 0; i < roleId.length; i++) {
                    RoleAuthority ra = new RoleAuthority();
                    ra.setRoleId(roleId[i]);
                    ra.setAuthority(String.valueOf(line.getId()));
                    roleAuthorityMapper.insertRecord(ra);
                }
            }
            map.put("success", true);
            map.put("message", "添加成功!");
            map.put("data", line);
        } else {
            String message = jo.getString("message");
            map.put("success", false);
            map.put("message", message);
        }
        return map;
    }

    @Override
    public Map<String, Object> updateLine(String id, Long companyId, String companyName,
        String name, String startCity,
        String startAddress, String endCity, String endAddress, Long areaId, Long jihuoAreaId,
        Long baocheAreaId, String contactNumber) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.UPDATE_LINE)
            .append("?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        if (StringUtils.isNotBlank(name)) {
            kv.put("name", name);
            builder.append("&name={name}");
        }
        if (StringUtils.isNotBlank(startCity)) {
            kv.put("startCity", startCity);
            builder.append("&startCity={startCity}");
        }
        if (StringUtils.isNotBlank(startAddress)) {
            kv.put("startAddress", startAddress);
            builder.append("&startAddress={startAddress}");
        }
        if (StringUtils.isNotBlank(endCity)) {
            kv.put("endCity", endCity);
            builder.append("&endCity={endCity}");
        }
        if (StringUtils.isNotBlank(endAddress)) {
            kv.put("endAddress", endAddress);
            builder.append("&endAddress={endAddress}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName", companyName);
            builder.append("&companyName={companyName}");
        }
        if (companyId != null) {
            kv.put("companyId", companyId + "");
            builder.append("&companyId={companyId}");
        }
        if (areaId != null) {
            kv.put("areaId", areaId + "");
            builder.append("&areaId={areaId}");
        }

        if (jihuoAreaId != null) {
            kv.put("jihuoAreaId", jihuoAreaId + "");
            builder.append("&jihuoAreaId={jihuoAreaId}");
        }

        if (baocheAreaId != null) {
            kv.put("baocheAreaId", baocheAreaId + "");
            builder.append("&baocheAreaId={baocheAreaId}");
        }
        if (null != contactNumber) {
            kv.put("contactNumber", contactNumber);
            builder.append("&contactNumber={contactNumber}");
        }

        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        Map<String, Object> map = new HashMap<String, Object>();
        if (code == 0) {
            map.put("success", true);
            map.put("message", "修改成功");
        } else {
            map.put("success", false);
            map.put("message", jo.getString("message"));
        }

        return map;
    }

    @Override
    public Map<String, Object> deleteCar(Long carId, Long[] lineId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.DELETE_CAR)
            .append(".json?lineId={lineId}&carId={carId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carId", String.valueOf(carId));
        StringBuilder lineStr = new StringBuilder();
        for (int i = 0; i < lineId.length; i++) {
            lineStr.append(lineId[i]);
            if (i < lineId.length - 1) {
                lineStr.append(",");
            }
        }
        kv.put("lineId", lineStr.toString());
        Car car = null;
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        Map<String, Object> map = new HashMap<String, Object>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                map.put("success", true);
                Driver driver = driverMapper.selectByZhuanxianCarId(carId);
                if (driver != null) {
                    driver.setZhuanxianCarId(null);
                    driverMapper.updateByPrimaryKey(driver);
                }
            } else {
                map.put("success", false);
                map.put("message", jo.getString("message"));
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> deleteLine(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.DELETE_LINE)
            .append(".json?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        Car car = null;
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        Map<String, Object> map = new HashMap<String, Object>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                map.put("success", true);
            } else {
                map.put("success", false);
                map.put("message", jo.getString("message"));
            }
        }
        return map;
    }

    @Override
    public Page<Map<String, Object>> orderListData(String orderNo, String passengerPhone,
        String employPhone,
        String companyName, String startTime, String endTime, String allorderType, String allstatus,
        Integer page,
        Integer rows, String treatment, String startFinishTime, String endFinishTime)
        throws ParseException {
        //分公司查询本公司数据
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        /** 获取用户的线路权限id */
        //获取当前登录账号的id
        Long adminId = principal.getId();
        //获取角色id
        List<AdminRole> arList = adminRoleMapper.selectByAdminId(adminId);
        Long roleId = arList.get(0).getRoleId();
        //获取角色绑定权限
        List<RoleAuthority> raList = roleAuthorityMapper.selectByRoleId(roleId);
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        String lineIdStr = "";
        for (RoleAuthority ra : raList) {
            String authority = ra.getAuthority();
            //判断是否为数字
            if (pattern.matcher(authority).matches()) {
                lineIdStr += authority + ",";
            }
        }
        if (lineIdStr.length() > 0) {
            lineIdStr = lineIdStr.substring(0, lineIdStr.length() - 1);
        }
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_ORDER)
            .append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (StringUtils.isNotBlank(lineIdStr)) {
            kv.put("lineIdStr", lineIdStr);
            builder.append("&lineIdStr={lineIdStr}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        kv.put("orderby", "status asc,id desc");
        builder.append("&orderby={orderby}");
        if (!principal.isCompanyType()) {//不是主公司时默认传本公司Id
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(orderNo)) {
            kv.put("orderNo", orderNo);
            builder.append("&orderNo={orderNo}");
        }
        if (StringUtils.isNotBlank(passengerPhone)) {
            kv.put("passengerName", passengerPhone);
            builder.append("&passengerName={passengerName}");
        }
        if (StringUtils.isNotBlank(employPhone)) {
            kv.put("employName", employPhone);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName",
                principal.isCompanyType() ? companyName : principal.getCompanyAbbreviation());
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            Date start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            kv.put("startTime", String.valueOf(start.getTime()));
            builder.append("&startTime={startTime}");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Date end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            kv.put("endTime", String.valueOf(end.getTime()));
            builder.append("&endTime={endTime}");
        }
        if (StringUtils.isNotBlank(startFinishTime)) {
            Date startFinish = DateUtils.parseDate(startFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("startFinishTime", String.valueOf(startFinish.getTime()));
            builder.append("&startFinishTime={startFinishTime}");
        }
        if (StringUtils.isNotBlank(endFinishTime)) {
            Date endFinish = DateUtils.parseDate(endFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("endFinishTime", String.valueOf(endFinish.getTime()));
            builder.append("&endFinishTime={endFinishTime}");
        }
        if (StringUtils.isNotBlank(allorderType)) {
            kv.put("allorderType", allorderType);
            builder.append("&allorderType={allorderType}");
        }
        if (StringUtils.isNotBlank(allstatus)) {
            kv.put("allstatus", allstatus);
            builder.append("&allstatus={allstatus}");
        }
        if ("true".equals(treatment)) {
            kv.put("treatment", String.valueOf(true));
            builder.append("&treatment={treatment}");
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        List<Order> list = new ArrayList<Order>();
        long total = 0;
        List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
            SimpleDateFormat format = new SimpleDateFormat("MM/dd HH:mm");
            for (Order order : list) {
                /**线路权限判定*/
                String lineId = order.getLineId().toString().trim();
                if (StringUtils.isNotBlank(lineId) && currentUser.isPermitted(lineId)) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    String orderType = "";
                    if (Order.TYPE_BAOCHE.equals(order.getOrderType())) {
                        orderType = "包车";
                    } else if (Order.TYPE_JIHUO.equals(order.getOrderType())) {
                        orderType = "寄货";
                    } else if (order.TYPE_PINCHE.equals(order.getOrderType())) {
                        orderType = "拼车";
                    }
                    map.put("id", order.getId());
                    map.put("orderType", orderType);
                    map.put("balanceMoney", order.getBalanceMoney());
                    map.put("budgetPay", order.getBudgetPay());
                    map.put("cancelCause",
                        order.getCancelCause() != null ? order.getCancelCause() : "-");
                    map.put("carId", order.getCarId());

                    map.put("carNumber", order.getCarNumber() != null ? order.getCarNumber() : "-");
                    map.put("lineId", order.getLineId());
                    map.put("lineName", order.getLineName());
                    map.put("channelName", order.getChannelName());
                    map.put("companyId", order.getCompanyId());
                    map.put("companyName", order.getCompanyName());
                    map.put("created", format.format(order.getCreated()));
                    map.put("employCompanyId", order.getEmployCompanyId());
                    map.put("employId", order.getEmployId());
                    map.put("peopleNumber", order.getPeopleNumber());
                    map.put("employName",
                        order.getEmployName() != null ? order.getEmployName() : "-");
                    map.put("employPhone", UseAllDataUtil.useAllDataDriver(
                        order.getEmployPhone() != null ? order.getEmployPhone() : "-"));
                    map.put("employProfit", order.getEmployProfit());
                    map.put("endAddress", order.getEndAddress());
                    map.put("endAddressDetail", order.getEndAddressDetail());
                    map.put("endlat", order.getEndLat());
                    map.put("endlng", order.getEndLng());
                    map.put("mileage", order.getMileage());
                    map.put("mileagePrice", order.getMileagePrice());
                    map.put("runtime", order.getRunTime());
                    map.put("startWait", order.getStartWait());
                    map.put("realPay", order.getRealPay());
                    map.put("preAndAfterPayType", order.getPreAndAfterPayType());
                    map.put("budgetPay", order.getBudgetPay());
                    map.put("orderNo", order.getOrderNo());
                    map.put("passengerId", order.getPassengerId());
                    map.put("passengerName", order.getPassengerName());
                    map.put("passengerPhone", UseAllDataUtil.useAllData(order.getPassengerPhone()));
                    map.put("justKilometres", order.getJustKilometres());
                    map.put("justMoney", order.getJustMoney());

                    if (StringUtils.isNotBlank(order.getShowPhone())) {
                        map.put("showPhone", UseAllDataUtil.useAllData(order.getShowPhone()));
                    } else {
                        map.put("showPhone", UseAllDataUtil.useAllData(order.getPassengerPhone()));
                    }

                    map.put("review", order.getReview());
                    map.put("serverTime", format.format(order.getServerTime()));
                    map.put("startAddress", order.getStartAddress());
                    map.put("startAddressDetail", order.getStartAddressDetail());
                    map.put("startLat", order.getStartLat());
                    map.put("startLng", order.getStartLng());
                    map.put("startPrice", order.getStartPrice());
                    map.put("status", order.getStatus());
                    map.put("guoluMoney", order.getGuoluMoney());
                    map.put("yuanchengMoney", order.getYuanchengMoney());
                    map.put("otherMoney", order.getOtherMoney());
                    String orderMemo = "";
                    if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                        List<OrderMemo> orderMemos = order.getOrderMemos();
                        for (int i = 0; i < orderMemos.size(); i++) {
                            orderMemo += ((i + 1) + ":");
                            orderMemo += (orderMemos.get(i).getMemo() + "\n");
                        }
                    }
                    map.put("orderMemo", orderMemo);

                    map.put("memoStr", order.getMemo());
                    map.put("couponId", order.getCouponId());
                    content.add(map);
                }

            }
        }

        return new PageImpl<Map<String, Object>>(content, pageable, total);
    }

    @Override
    public List<Map<String, Object>> orderListDataExport(String orderNo, String passengerPhone,
        String employPhone,
        String companyName, String startTime, String endTime, String allorderType, String allstatus,
        String treatment, String startFinishTime, String endFinishTime) throws ParseException {
        //分公司查询本公司数据
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_ORDER)
            .append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("orderby", "status asc,id desc");
        builder.append("&orderby={orderby}");
        if (!principal.isCompanyType()) {//不是主公司时默认传本公司Id
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }
        if (StringUtils.isNotBlank(orderNo)) {
            kv.put("orderNo", orderNo);
            builder.append("&orderNo={orderNo}");
        }
        if (StringUtils.isNotBlank(passengerPhone)) {
            kv.put("passengerName", passengerPhone);
            builder.append("&passengerName={passengerName}");
        }
        if (StringUtils.isNotBlank(employPhone)) {
            kv.put("employName", employPhone);
            builder.append("&employName={employName}");
        }
        if (StringUtils.isNotBlank(companyName)) {
            kv.put("companyName",
                principal.isCompanyType() ? companyName : principal.getCompanyAbbreviation());
            builder.append("&companyName={companyName}");
        }
        if (StringUtils.isNotBlank(startTime)) {
            Date start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            kv.put("startTime", String.valueOf(start.getTime()));
            builder.append("&startTime={startTime}");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Date end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            kv.put("endTime", String.valueOf(end.getTime()));
            builder.append("&endTime={endTime}");
        }
        if (StringUtils.isNotBlank(startFinishTime)) {
            Date startFinish = DateUtils.parseDate(startFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("startFinishTime", String.valueOf(startFinish.getTime()));
            builder.append("&startFinishTime={startFinishTime}");
        }
        if (StringUtils.isNotBlank(endFinishTime)) {
            Date endFinish = DateUtils.parseDate(endFinishTime, "yyyy-MM-dd HH:mm");
            kv.put("endFinishTime", String.valueOf(endFinish.getTime()));
            builder.append("&endFinishTime={endFinishTime}");
        }
        if (StringUtils.isNotBlank(allorderType)) {
            kv.put("allorderType", allorderType);
            builder.append("&allorderType={allorderType}");
        }
        if (StringUtils.isNotBlank(allstatus)) {
            kv.put("allstatus", allstatus);
            builder.append("&allstatus={allstatus}");
        }
        if ("true".equals(treatment)) {
            kv.put("treatment", String.valueOf(true));
            builder.append("&treatment={treatment}");
        }

        builder.append("&page={page}");
        builder.append("&rows={rows}");

        Integer rows = 100;
        Integer currentRows = 0;
        Integer page = 0;

        kv.put("page", String.valueOf(page + 1));
        kv.put("rows", String.valueOf(rows));

        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        List<Map<String, Object>> content = new ArrayList<Map<String, Object>>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Long total = 0l;
                List<Order> list = new ArrayList<Order>();
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());

                if (total > 0) {
                    currentRows += rows;
                    page++;
                    while (currentRows < total) {
                        kv.put("page", String.valueOf(page + 1));
                        kv.put("rows", String.valueOf(rows));
                        String result2 = zhuanxianApi
                            .get(builder.toString(), kv, settingUtils.get());
                        if (null != result2) {
                            JSONObject jo2 = new JSONObject(result2);
                            Integer code2 = jo2.getInt("code");
                            if (code2 == 0) {
                                Long total2 = 0l;
                                List<Order> list2 = new ArrayList<Order>();
                                JSONObject data2 = jo2.getJSONObject("data");
                                total2 = data.getLong("total");
                                JSONArray ja2 = data2.getJSONArray("rows");
                                list2 = gson.fromJson(ja2.toString(), new TypeToken<List<Order>>() {
                                }.getType());
                                if (total2 > 0) {
                                    list.addAll(list2);
                                }
                            }
                        }
                        currentRows += rows;
                        page++;
                    }

                    SimpleDateFormat format = new SimpleDateFormat("MM/dd HH:mm");
                    for (Order order : list) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        String orderType = "";
                        if (Order.TYPE_BAOCHE.equals(order.getOrderType())) {
                            orderType = "包车";
                        } else if (Order.TYPE_JIHUO.equals(order.getOrderType())) {
                            orderType = "寄货";
                        } else if (Order.TYPE_PINCHE.equals(order.getOrderType())) {
                            orderType = "拼车";
                        }
                        map.put("id", order.getId());
                        map.put("orderType", orderType);
                        map.put("balanceMoney", order.getBalanceMoney());
                        map.put("budgetPay", order.getBudgetPay());
                        map.put("cancelCause",
                            order.getCancelCause() != null ? order.getCancelCause() : "-");
                        map.put("carId", order.getCarId());

                        map.put("carNumber",
                            order.getCarNumber() != null ? order.getCarNumber() : "-");
                        map.put("lineId", order.getLineId());
                        map.put("lineName", order.getLineName());
                        map.put("channelName", order.getChannelName());
                        map.put("companyId", order.getCompanyId());
                        map.put("companyName", order.getCompanyName());
                        map.put("created", format.format(order.getCreated()));
                        map.put("employCompanyId", order.getEmployCompanyId());
                        map.put("employId", order.getEmployId());
                        map.put("peopleNumber", order.getPeopleNumber());
                        map.put("employName",
                            order.getEmployName() != null ? order.getEmployName() : "-");
                        map.put("employPhone", UseAllDataUtil.useAllDataDriver(
                            order.getEmployPhone() != null ? order.getEmployPhone() : "-"));
                        map.put("employProfit", order.getEmployProfit());
                        map.put("endAddress", order.getEndAddress());
                        map.put("endAddressDetail", order.getEndAddressDetail());
                        map.put("endlat", order.getEndLat());
                        map.put("endlng", order.getEndLng());
                        map.put("mileage", order.getMileage());
                        map.put("mileagePrice", order.getMileagePrice());
                        map.put("runtime", order.getRunTime());
                        map.put("startWait", order.getStartWait());
                        map.put("realPay", order.getRealPay());
                        map.put("preAndAfterPayType", order.getPreAndAfterPayType());
                        map.put("budgetPay", order.getBudgetPay());
                        map.put("orderNo", order.getOrderNo());
                        map.put("passengerId", order.getPassengerId());
                        map.put("passengerName", order.getPassengerName());
                        map.put("passengerPhone",
                            UseAllDataUtil.useAllData(order.getPassengerPhone()));
                        map.put("justKilometres", order.getJustKilometres());
                        map.put("justMoney", order.getJustMoney());

                        if (StringUtils.isNotBlank(order.getShowPhone())) {
                            map.put("showPhone", UseAllDataUtil.useAllData(order.getShowPhone()));
                        } else {
                            map.put("showPhone",
                                UseAllDataUtil.useAllData(order.getPassengerPhone()));
                        }

                        map.put("review", order.getReview());
                        map.put("serverTime", format.format(order.getServerTime()));
                        map.put("startAddress", order.getStartAddress());
                        map.put("startAddressDetail", order.getStartAddressDetail());
                        map.put("startLat", order.getStartLat());
                        map.put("startLng", order.getStartLng());
                        map.put("startPrice", order.getStartPrice());
                        map.put("status", order.getStatus());
                        map.put("guoluMoney", order.getGuoluMoney());
                        map.put("yuanchengMoney", order.getYuanchengMoney());
                        map.put("otherMoney", order.getOtherMoney());
                        String orderMemo = "";
                        if (order.getOrderMemos() != null && order.getOrderMemos().size() != 0) {
                            List<OrderMemo> orderMemos = order.getOrderMemos();
                            for (int i = 0; i < orderMemos.size(); i++) {
                                orderMemo += ((i + 1) + ":");
                                orderMemo += (orderMemos.get(i).getMemo() + "\n");
                            }
                        }
                        map.put("orderMemo", orderMemo);

                        map.put("memoStr", order.getMemo());
                        map.put("couponId", order.getCouponId());
                        content.add(map);
                    }

                }
            }

        }

        return content;
    }

    @Override
    public List<Car> findCarByNumber(String carNumber) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_CAR_CARNUMBER)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("carNumber", carNumber);
        builder.append("&carNumber={carNumber}");

        List<Car> list = new ArrayList<Car>();
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public Order findOne(Long id) {
        Order order = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_ONE_ORDER)
            .append("?orderId={orderId}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(id));
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                order = gson.fromJson(data.toString(), Order.class);
            }
        }
        return order;
    }

    @Override
    public Line findByLine(Long lineId) {
        Line line = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_LINE)
            .append("?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(lineId));
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                if (jo.get("data") != JSONObject.NULL) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .serializeNulls().create();
                    line = gson.fromJson(data.toString(), Line.class);
                }

            }
        }
        return line;
    }

    @Override
    public Result<List<Order>> createOrder(Integer orderType, Long peopleNumber, Long passengerId,
        String passengerName, String passengerPhone, Long companyId,
        String companyName, Long lineId, String startAddress, Double startLat, Double startLng,
        String endAddress,
        Double endLat, Double endLng, Date startDate, Double budgetPay, Double startPrice,
        Double mileagePrice,
        Double runTimePrice, Integer travelTime, Double mileage, String channelName, Long couponId,
        String takeDeliveryName, String takeDeliveryPhone,
        String operator, String memo) {

        Setting setting = settingUtils.get();
        Result<List<Order>> r = new Result<List<Order>>();
        Passenger passenger = new Passenger();
        if (passengerId == null) {
            if (StringUtils.isNotBlank(passengerName)) {
                passenger.setName(passengerName);
            } else {
                passenger.setName("先生/女士");
            }
            passenger.setPhone(passengerPhone);
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_PHONE);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setAllowOverdraw(false);
            passenger.setLongitude(startLng);
            passenger.setLatitude(startLat);
            passenger.setCompanyId(companyId);
            passenger.setCompanyName(companyName);
            try {
                Result<Passenger> result = passengerApi
                    .createPersonal(passenger, settingUtils.get());
                passenger = result.getResult();
                if (passenger.getId() == null || passenger.getId() == 0) {
                    r.setMessage("创建新乘客失败!");
                    r.setSuccess(false);
                    return r;
                }
            } catch (Exception e) {
                e.printStackTrace();
                r.setMessage("创建新乘客失败!");
                r.setSuccess(false);
                return r;
            }

        } else {
            Result<Passenger> result = passengerApi
                .findOnePassenger(passengerId, settingUtils.get());
            passenger = result.getResult();
        }
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("passengerId", String.valueOf(passenger.getId()));
        kv.add("passengerName", passenger.getName());
        kv.add("orderType", orderType + "");
        kv.add("passengerPhone", passenger.getPhone());
        kv.add("companyId", String.valueOf(companyId));
        kv.add("companyName", companyName);
        kv.add("lineId", String.valueOf(lineId));
        kv.add("channelName", channelName);
        kv.add("startAddress", startAddress);
        kv.add("startLat", String.valueOf(startLat));
        kv.add("startLng", String.valueOf(startLng));
        kv.add("memo", memo);
        if (couponId != null) {
            kv.add("couponId", couponId + "");
        }
        if (peopleNumber != null) {
            kv.add("peopleNumber", peopleNumber + "");
        }
        kv.add("endAddress", endAddress);
        kv.add("endLat", String.valueOf(endLat));
        kv.add("endLng", String.valueOf(endLng));
        kv.add("startTime", String.valueOf(startDate.getTime()));
        if (StringUtils.isNotBlank(operator)) {
            kv.add("serverDeadTime", String.valueOf(setting.getBookTimeZhuanxian()));
        }

        budgetPay = new BigDecimal(new DecimalFormat("#.00").format(budgetPay)).doubleValue();
        kv.add("budgetPay", String.valueOf(budgetPay));
        kv.add("system", String.valueOf(true));

        if (StringUtils.isNotBlank(operator)) {
            kv.add("operator", operator);
        }
        if (StringUtils.isNotBlank(takeDeliveryName)) {
            kv.add("takeDeliveryName", takeDeliveryName);
        }
        if (StringUtils.isNotBlank(takeDeliveryPhone)) {
            kv.add("takeDeliveryPhone", takeDeliveryPhone);
        }
        String result = zhuanxianApi
            .post(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.CREATE_ORDER, kv,
                settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                List<Order> orders = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
                r.setResult(orders);
                r.setSuccess(true);
	              /*  if (employId != null && order.getStatus() == 1) {
	                    driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_ACCEPT_ORDER, Driver.DRIVER_JOBSTATUS_ZHUANCHE, employId);
	                }*/
            } else {
                String message = jo.getString("message");
                r.setMessage(message);
                r.setSuccess(false);
            }
        }
        return r;
    }

    @Override
    public List<Line> getLinesByCar(Long carId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.FIND_LINES_BY_CAR)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("carId", String.valueOf(carId));
        builder.append("&carId={carId}");

        List<Line> list = new ArrayList<Line>();
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Line>>() {
                }.getType());
            }
        }
        return list;


    }

    @Override
    public List<Order> listNewOrders() {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.FIND_NEW_ORDER)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        if (!principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }

        kv.put("page", "1");
        builder.append("&page={page}");

        kv.put("rows", "20");
        builder.append("&rows={rows}");

        List<Order> list = new ArrayList<Order>();
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }

        return list;
    }

    @Override
    public List<Order> findActivedOrdersByDriver(Long employId) {

        return zhuanxianApi.findActivedOrdersByDriver(employId, settingUtils.get());

    }

    @Override
    public void remark(Long id, String memo) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(id));
        kv.add("memo", memo);
        kv.add("operator", operator);

        String result = zhuanxianApi
            .post(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.CREATE_ORDERMEMO, kv,
                settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code != 0) {
                throw new RuntimeException();
            }
        }
    }

    //销单
    @Override
    public Result<Order> cancelOrder(Order order, String cancelCause, String operator) {
        Subject currentUser = SecurityUtils.getSubject();
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);
        result.setMessage("销单失败");
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.CANCEL_ORDER)
            .append("?orderId={orderId}&operator={operator}&cause={cause}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("cause", cancelCause);
        kv.put("operator", operator);

        String resultStr = zhuanxianApi.post(builder.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                result.setSuccess(true);
                result.setMessage("销单成功");

                ZhuanxianOrderCancelEvent cancelEvent = new ZhuanxianOrderCancelEvent(order.getId(),
                    order.getEmployId(), PushMessage.FROM_ADMIN);
                applicationEventMulticaster.multicastEvent(cancelEvent);

                //销单退款
                if (null != order.getPrePayTypeDetail() && !order.getPrePayTypeDetail()
                    .equals(PayTypeDetails.coupon)) {
                    Result<Passenger> result_p = passengerApi
                        .findOnePassenger(order.getPassengerId(), settingUtils.get());
                    Passenger passenger = result_p.getResult();
                    if (null != passenger) {
                        BigDecimal coupon_hasPayed = BigDecimal.ZERO;
                        if (null != order.getCouponId()) {
                            Coupon coupon = salesApi.findOneCoupon(order.getCouponId()).getResult();
                            if (null != coupon) {
                                if (coupon.getCouponRule().getType()
                                    .equals(CouponRule.TYPE_DEDUCTION)) {
//                                    coupon_hasPayed = coupon.getCouponRule().getMoney();
                                    coupon_hasPayed = coupon.getCouponPrice();
                                } else if (coupon.getCouponRule().getType()
                                    .equals(CouponRule.TYPE_DISCOUNT)) {
//                                    Double discount = coupon.getCouponRule().getDiscount();
                                    Double discount = coupon.getCouponDiscount();
                                    coupon_hasPayed = new BigDecimal(order.getBudgetPay()).multiply(
                                        new BigDecimal(1).subtract(
                                            new BigDecimal(discount).divide(new BigDecimal(10))))
                                        .setScale(0, BigDecimal.ROUND_DOWN);
                                }
                            }
                        }
                        BigDecimal tuikuan = new BigDecimal(order.getBudgetPay())
                            .subtract(coupon_hasPayed);
                        if (tuikuan.doubleValue() > 0) {
                            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                                passengerApi.createPassengerAccount(passenger, null, tuikuan,
                                    PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                    PassengerAccount.OPERATING_SYS, "销单退款:" + cancelCause,
                                    order.getId(), order.getOrderNo(),
                                    PassengerAccount.ORDER_TYPE_ZHUANXIAN, null, true, false,
                                    settingUtils.get());
                            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                                Enterprise enterprise = passengerApi
                                    .findOneEnterprise(passenger.getEnterprise_id(),
                                        settingUtils.get()).getResult();
                                if (null != enterprise) {
                                    passengerApi.createEnterpriseAccount(enterprise, tuikuan,
                                        PassengerAccount.PayType.RECHARGE_TYPE_CANCEL_RETURN,
                                        PassengerAccount.OPERATING_SYS, "销单退款:" + cancelCause,
                                        order.getId(), order.getOrderNo(),
                                        PassengerAccount.ORDER_TYPE_ZHUANXIAN, null, true, false,
                                        settingUtils.get());
                                }
                            }
                        }
                    }
                }
            }
        }

        return result;
    }

    @Override
    public ChartYear dataForYear(Integer year, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.ORDERSTATISTICS)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        ChartYear chartYear = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                chartYear = gson.fromJson(data.toString(), ChartYear.class);
            }
        }

        return chartYear;
    }

    @Override
    public ChartMonth zhuanxianDataForMonth(Integer year, Integer month, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.ORDERSTATISTICSMONTH)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        ChartMonth chartMonth = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                chartMonth = gson.fromJson(data.toString(), ChartMonth.class);
            }
        }
        return chartMonth;
    }

    @Override
    public ChartDay zhuanxianDataForDay(Integer year, Integer month, Integer day, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.ORDERSTATISTICSDAY)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (day != null) {
            builder.append("&day={day}");
            kv.put("day", String.valueOf(day));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        ChartDay chartDay = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                chartDay = gson.fromJson(data.toString(), ChartDay.class);
            }
        }

        return chartDay;
    }

    @Override
    public List<TableOrderMonthVo> tableOrderMonth(Integer year, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.ORDERSTATISTICS)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        ChartYear chartYear = null;
        List<TableOrderMonthVo> lists = new ArrayList<TableOrderMonthVo>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                chartYear = gson.fromJson(data.toString(), ChartYear.class);
                for (ChartMonth month : chartYear.getMonths()) {
                    TableOrderMonthVo tomv = new TableOrderMonthVo();
                    tomv.setCancelAmount(month.getTotalCancelNum());
                    tomv.setFinishedAmount(month.getTotalSuccessNum());
                    tomv.setMoney(month.getTotalPrice());
                    tomv.setTime(month.getMonth());
                    lists.add(tomv);
                }
            }

        }
        return lists;
    }

    @Override
    public PageVo<OrderFromSourceVo> orderFromSource(Date start, Date end, Long companyId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.ORDERTYPESTATISTICS)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startDate={startDate}");
            kv.put("startDate", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endDate={endDate}");
            kv.put("endDate", end.getTime() + "");
        }

        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<OrderFromSourceVo> orderFromSourceVos = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                orderFromSourceVos = gson
                    .fromJson(data.toString(), new TypeToken<PageVo<OrderFromSourceVo>>() {
                    }.getType());
            }
        }

        return orderFromSourceVos;
    }

    @Override
    public PageVo<MemberOrderVo> zhuanxianMemberOrder(Date start, Date end, Long companyId,
        Long gradeId,
        Integer type) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder sb2 = new StringBuilder();
        sb2.append(passengerApi.getPassengerBaseURL()).append(PassengerApi.QUERY_PASSENGER)
            .append("?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");

        Map<String, String> kv2 = new HashMap<String, String>();
        kv2.put("page", String.valueOf(Pager.getPage() + 1));
        kv2.put("rows", String.valueOf(Pager.getLimit()));
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv2.put("companyId", String.valueOf(companyId));
                sb2.append("&companyId={companyId}");
            }
        } else {
            kv2.put("companyId", String.valueOf(principal.getCompanyId()));
            sb2.append("&companyId={companyId}");
        }

        if (null != gradeId) {
            kv2.put("gradeId", String.valueOf(gradeId));
            sb2.append("&gradeId={gradeId}");
        }
        if (null != type) {
            kv2.put("type", String.valueOf(type));
            sb2.append("&type={type}");
        }

        String result2 = passengerApi.get(sb2.toString(), kv2, settingUtils.get());

        List<Passenger> content2 = new ArrayList<Passenger>();
        long total = 0;

        if (null != result2) {
            JSONObject jo = new JSONObject(result2);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                content2 = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }
        StringBuilder sb1 = new StringBuilder();
        sb1.append(passengerApi.getPassengerBaseURL()).append(PassengerApi.QUERY_PASSENGER)
            .append("?appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv1 = new HashMap<String, String>();

        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv1.put("companyId", String.valueOf(companyId));
                sb1.append("&companyId={companyId}");
            }
        } else {
            kv1.put("companyId", String.valueOf(principal.getCompanyId()));
            sb1.append("&companyId={companyId}");
        }

        if (null != gradeId) {
            kv1.put("gradeId", String.valueOf(gradeId));
            sb1.append("&gradeId={gradeId}");
        }
        if (null != type) {
            kv1.put("type", String.valueOf(type));
            sb1.append("&type={type}");
        }

        String result1 = passengerApi.get(sb1.toString(), kv1, settingUtils.get());

        List<Passenger> findAll = new ArrayList<Passenger>();

        if (null != result1) {
            JSONObject jo = new JSONObject(result1);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                findAll = gson.fromJson(ja.toString(), new TypeToken<List<Passenger>>() {
                }.getType());
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.ZHUANXIANMEMBERORDER)
            .append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();

        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (null != start) {
            kv.put("startTime", String.valueOf(start.getTime()));
            sb.append("&startTime={startTime}");
        }
        if (null != end) {
            kv.put("endTime", String.valueOf(end.getTime()));
            sb.append("&endTime={endTime}");
        }

        String result = zhuanxianApi.get(sb.toString(), kv, settingUtils.get());
        PageVo<MemberOrderVo> content = new PageVo<MemberOrderVo>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                content = gson.fromJson(data.toString(), new TypeToken<PageVo<MemberOrderVo>>() {
                }.getType());
            }
        }

        PageVo<MemberOrderVo> vopage = new PageVo<MemberOrderVo>();
        List<MemberOrderVo> volist = new ArrayList<MemberOrderVo>();
        MemberOrderVo count = new MemberOrderVo();
        count.setName("总计");
        count.setPhone("");
        count.setCompanyName(" ");
        count.setMoney(BigDecimal.ZERO);
        for (Passenger passenger : findAll) {
            for (MemberOrderVo memberOrderVo : content.getContent()) {
                if (passenger.getId().equals(memberOrderVo.getId())) {
                    count.setFinishNums(count.getFinishNums() + memberOrderVo.getFinishNums());
                    count.setMoney(count.getMoney().add(memberOrderVo.getMoney()));
                }
            }
        }

        MemberOrderVo count2 = new MemberOrderVo();
        count2.setName("当前页总计");
        count2.setPhone("");
        count2.setCompanyName(" ");
        count2.setMoney(BigDecimal.ZERO);

        for (Passenger passenger : content2) {
            MemberOrderVo mv = new MemberOrderVo();
            mv.setId(passenger.getId());
            mv.setName(passenger.getName());
            mv.setPhone(passenger.getPhone());
            mv.setCompanyName(passenger.getCompanyName());
            for (MemberOrderVo memberOrderVo : content.getContent()) {
                if (passenger.getId().equals(memberOrderVo.getId())) {
                    mv.setFinishNums(memberOrderVo.getFinishNums());
                    mv.setMoney(memberOrderVo.getMoney());
                    break;

                }
            }
            volist.add(mv);
            count2.setFinishNums(count2.getFinishNums() + mv.getFinishNums());
            count2.setMoney(count2.getMoney().add(mv.getMoney()));
        }

        volist.add(count2);
        volist.add(count);
        vopage.setContent(volist);
        vopage.setTotalElements(findAll.size());
        return vopage;
    }

    @Override
    public PageVo<DriverOrderVo> zhuanxianIntroduce(Long companyId, Date start, Date end) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.DRIVERACHIEVEMENT)
            .append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        if (principal.isCompanyType()) {
            if (null != companyId) {
                kv.put("companyId", String.valueOf(companyId));
                sb.append("&companyId={companyId}");
            }
        } else {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            sb.append("&companyId={companyId}");
        }
        if (start != null) {
            kv.put("startDate", String.valueOf(start.getTime()));
            sb.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", String.valueOf(end.getTime()));
            sb.append("&endDate={endDate}");
        }

        String result = zhuanxianApi.get(sb.toString(), kv, settingUtils.get());

        PageVo<DriverOrderVo> list = new PageVo<DriverOrderVo>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<PageVo<DriverOrderVo>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public PageVo<DriverOrderDetailVo> driverOrderDetail(Long driverId, Date start, Date end) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.DRIVERORDERDETAILVO)
            .append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (driverId != null) {
            kv.put("driverId", driverId + "");
            builder.append("&driverId={driverId}");
        }
        if (start != null) {
            kv.put("startDate", start.getTime() + "");
            builder.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", end.getTime() + "");
            builder.append("&endDate={endDate}");
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<DriverOrderDetailVo> page = new PageVo<DriverOrderDetailVo>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                page = gson.fromJson(data.toString(), new TypeToken<PageVo<DriverOrderDetailVo>>() {
                }.getType());
            }
        }

        return page;
    }

    @Override
    public PageVo<CompanyOrderVo> companyOrder(Date start, Date end) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL())
            .append(ZhuanxianApi.COMPANYORDERSTATISTICS).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startDate={startDate}");
            kv.put("startDate", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endDate={endDate}");
            kv.put("endDate", end.getTime() + "");
        }

        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<CompanyOrderVo> companyOrderVos = null;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                companyOrderVos = gson
                    .fromJson(data.toString(), new TypeToken<PageVo<CompanyOrderVo>>() {
                    }.getType());
            }
        }
        List<Company> companys = companyMapper.selectAll();
        List<CompanyOrderVo> vos = new ArrayList<CompanyOrderVo>();
        for (Company company : companys) {
            CompanyOrderVo vo = new CompanyOrderVo();
            vo.setCompanyName(company.getAbbreviation());
            for (CompanyOrderVo vo1 : companyOrderVos.getContent()) {
                if (vo1.getCompanyName().equals(vo.getCompanyName())) {
                    vo.setCancelNums(vo1.getCancelNums());
                    vo.setFinishNums(vo1.getFinishNums());
                    vo.setMoney(vo1.getMoney());
                    break;
                }
            }
            vos.add(vo);
        }
        companyOrderVos.setContent(vos);
        companyOrderVos.setTotalElements(vos.size());

        return companyOrderVos;
    }

    @Override
    public Result<Order> callback(Long id, Driver driver, String cause) {
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.CALLBACK + "?appKey={appKey}");
        sb.append("&orderId={orderId}");
        sb.append("&operator={operator}");
        sb.append("&cause={cause}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(id));
        kv.put("cause", cause);
        kv.put("operator", operator);

        String resultStr = zhuanxianApi.post(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            if (jo.getInt("code") == 0) {
                result.setMessage("收回成功");
                result.setSuccess(true);

                if (null != driver) {
                    List<Order> os = this.queryRunOrderByEmploy(driver.getId());
                    if (CollectionUtils.isEmpty(os)) {
                        if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                            driverService.updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null,
                                driver.getId());
                        }
                    }
                }
            } else {
                result.setMessage(jo.getString("message"));
                result.setSuccess(false);
            }
        } else {
            result.setSuccess(false);
        }

        return result;
    }

    @Override
    public Result<Order> autoCallback(Order order, Driver driver) {
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.CALLBACK + "?appKey={appKey}");
        sb.append("&orderId={orderId}");
        sb.append("&operator={operator}");
        sb.append("&cause={cause}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("cause", "时间逾期，系统自动收回了该订单");
        kv.put("operator", "系统");

        String resultStr = zhuanxianApi.post(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            if (jo.getInt("code") == 0) {
                result.setMessage("收回成功");
                result.setSuccess(true);

                if (null != driver) {
                    List<Order> os = this.queryRunOrderByEmploy(driver.getId());
                    if (CollectionUtils.isEmpty(os)) {
                        if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                            driverService.updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null,
                                driver.getId());
                        }
                    }
                }
            } else {
                result.setMessage(jo.getString("message"));
                result.setSuccess(false);
            }
        } else {
            result.setSuccess(false);
        }

        return result;
    }

    @Override
    public void revoke(Order order, String string) {
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);
        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.CALLBACK)
            .append("?appKey={appKey}");
        sb.append("&orderId={orderId}");
        sb.append("&operator={operator}");
        sb.append("&cause={cause}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(order.getId()));
        kv.put("cause", string);
        kv.put("operator", "系统");
        String resultStr = zhuanxianApi.post(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            if (jo.getInt("code") == 0) {
                result.setSuccess(true);
                result.setMessage("收回订单成功");
                Driver driver = driverService.findOne(order.getEmployId());
                if (driver != null) {
                    ZhuanxianOrderCallBackEvent callBackEvent = new ZhuanxianOrderCallBackEvent(
                        order, driver);
                    applicationEventMulticaster.multicastEvent(callBackEvent);
                    List<Order> activedList = this.findActivedOrdersByDriver(driver.getId());
                    long pai = 0;
                    long jie = 0;
                    long arrive = 0;
                    long busy = 0;
                    if (!CollectionUtils.isEmpty(activedList)) {
                        for (Order activedOrder : activedList) {
                            if (!activedOrder.getId().equals(order.getId())) {
                                if (activedOrder.getStatus().equals(Order.ORDER_STATUS_PAIDAN)) {
                                    ++pai;
                                } else if (activedOrder.getStatus()
                                    .equals(Order.ORDER_STATUS_JIEDAN)) {
                                    ++jie;
                                } else if (activedOrder.getStatus()
                                    .equals(Order.ORDER_STATUS_ARRIVE)) {
                                    ++arrive;
                                } else if (activedOrder.getStatus()
                                    .equals(Order.ORDER_STATUS_ZHIXING)) {
                                    ++busy;
                                }
                            }
                        }
                    }
                    if (busy > 0 || arrive > 0 || jie > 0) {
                        if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                            driverService.updateStatusAndJobStatus(Driver.DRIVER_BUSY,
                                Driver.DRIVER_JOBSTATUS_ZHUANXIAN, driver.getId());
                        }
                    } else if (pai > 0) {
                        if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                            driverService.updateStatusAndJobStatus(Driver.DRIVER_APPLY_ORDER,
                                Driver.DRIVER_JOBSTATUS_ZHUANXIAN, driver.getId());
                        }
                    } else {
                        if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                            driverService.updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null,
                                driver.getId());
                        }
                    }
                }

            } else {
                result.setSuccess(false);
                result.setMessage("收回订单失败");
            }

        } else {
            result.setSuccess(false);
            result.setMessage("收回订单失败");
        }
    }

    @Override
    public Long countUsedSeatingByDriver(Long employId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL())
            .append(ZhuanxianApi.QUERY_EMPLOY_USEDSEATING).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        if (employId != null) {
            kv.put("employId", employId + "");
            builder.append("&employId={employId}");
        }
        Long count = 0L;
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                count = jo.getLong("data");
            }
        }

        return count;
    }

    @Override
    public Result<Order> paidan(Driver driver, Order order) {
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();
        String operatorMemo = "管理员【" + operator + "】" + "将订单指派给" + driver.getRealname();

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL()).append(
            ZhuanxianApi.ORDER_PAIDAN);//.append("?orderId={orderId}&operator={operator}&operatorMemo={operatorMemo}&appKey={appKey}");
        //Map<String,String> kv = new HashMap<String,String>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("operator", operator);
        kv.add("operatorMemo", operatorMemo);
        kv.add("orderId", String.valueOf(order.getId()));

        //  sb.append("&employId={employId}&employName={employName}&employPhone={employPhone}&employNo={employNo}&employPhoto={employPhoto}&employScore={employScore}&employCompanyId={employCompanyId}");
        kv.add("employId", String.valueOf(driver.getId()));
        kv.add("employName", driver.getName());
        kv.add("employPhone", driver.getPhone());
        kv.add("employNo", driver.getUsername());
        Setting setting = settingUtils.get();
        kv.add("employPhoto", setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
        kv.add("employScore", String.valueOf(driver.getStarLevel()));
        kv.add("employCompanyId", String.valueOf(driver.getCompanyId()));
        //String resultStr = zhuanxianApi.post(sb.toString(), kv, setting);
        String resultStr = zhuanxianApi.postMultiValueMap(sb.toString(), kv, setting);
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            int code = jo.getInt("code");
            if (code == 0) {
                result.setSuccess(true);
                if (driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
                    driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
                        Driver.DRIVER_JOBSTATUS_ZHUANXIAN, driver.getId());
                }

                //自动收回
                if (setting.getRevokeTime() != 0) {
                    try {
                        //专车订单自动收回定时器
                        Timer timer = new Timer();
                        OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(
                            order.getId(), "zhuanxian", applicationEventMulticaster);
                        Integer howLong = setting.getRevokeTime();
                        timer.schedule(orderRevokeTimerTask, howLong * 1000);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    @Override
    public Result<Order> autoPaidan(Driver driver, Order order) {
        Result<Order> result = new Result<Order>();
        result.setSuccess(false);

        String operator = "系统";
        String operatorMemo = "系统自动将订单指派给" + driver.getRealname();

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL()).append(
            ZhuanxianApi.ORDER_AUTO_PAIDAN);//.append("?orderId={orderId}&operator={operator}&operatorMemo={operatorMemo}&appKey={appKey}");
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        //Map<String,String> kv = new HashMap<String,String>();

        kv.add("operator", operator);
        kv.add("operatorMemo", operatorMemo);
        kv.add("orderId", String.valueOf(order.getId()));

        // sb.append("&employId={employId}&employName={employName}&employPhone={employPhone}&employNo={employNo}&employPhoto={employPhoto}&employScore={employScore}&employCompanyId={employCompanyId}");
        kv.add("employId", String.valueOf(driver.getId()));
        kv.add("employName", driver.getRealname());
        kv.add("employPhone", driver.getPhone());
        kv.add("employNo", driver.getUsername());
        Setting setting = settingUtils.get();
        kv.add("employPhoto", setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
        kv.add("employScore", String.valueOf(driver.getStarLevel()));
        kv.add("employCompanyId", String.valueOf(driver.getCompanyId()));
        //String resultStr = zhuanxianApi.post(sb.toString(), kv, setting);
        String resultStr = zhuanxianApi.postMultiValueMap(sb.toString(), kv, setting);
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            int code = jo.getInt("code");
            if (code == 0) {
                result.setSuccess(true);
                if (driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
                    driverMapper.updateStatusAndJobStatusByPrimaryKey(Driver.DRIVER_APPLY_ORDER,
                        Driver.DRIVER_JOBSTATUS_ZHUANXIAN, driver.getId());
                }
                ZhuanxianOrderPaidanEvent paidanEvent = new ZhuanxianOrderPaidanEvent(order);
                applicationEventMulticaster.multicastEvent(paidanEvent);

                //自动收回
                if (setting.getRevokeTime() != 0) {
                    try {
                        //专车订单自动收回定时器
                        Timer timer = new Timer();
                        OrderRevokeTimerTask orderRevokeTimerTask = new OrderRevokeTimerTask(
                            order.getId(), "zhuanxian", applicationEventMulticaster);
                        Integer howLong = setting.getRevokeTime();
                        timer.schedule(orderRevokeTimerTask, howLong * 1000);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            } else {
                result.setSuccess(false);
                result.setMessage(jo.getString("message"));
            }
        }
        return result;
    }

    @Override
    public Long countOrderFinishedBycompanyId(Long companyId, Date start,
        Date end, Long lineId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_ORDER)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (start != null) {
            builder.append("&startFinishTime={startFinishTime}");
            kv.put("startFinishTime", start.getTime() + "");
        }
        if (end != null) {
            builder.append("&endFinishTime={endFinishTime}");
            kv.put("endFinishTime", end.getTime() + "");
        }
        builder.append("&allstatus=5");
        if (companyId != null) {
            builder.append("&companyId={companyId}");
            kv.put("companyId", String.valueOf(companyId));
        }
        if (lineId != null) {
            builder.append("&lineId={lineId}");
            kv.put("lineId", String.valueOf(lineId));
        }
        //先这样了
        builder.append("&page={page}");
        kv.put("page", String.valueOf(1));
        builder.append("&rows={rows}");
        kv.put("rows", String.valueOf(1));

        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        Long total = 0l;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
            }
        }

        return total;
    }

    @Override
    public List<Order> findOrderFinishedBycompanyId(Long companyId, Date start, Date end,
        Long lineId) {

        Long total = countOrderFinishedBycompanyId(companyId, start, end, lineId);
        List<Order> list = new ArrayList<Order>();

        if (total > 0) {
            Integer rows = 100;
            Integer totalPage = (int) (total / rows);
            if (total % rows != 0) {
                totalPage++;
            }
            Integer page = 1;
            while (page <= totalPage) {

                StringBuilder builder = new StringBuilder();
                builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_ORDER)
                    .append("?appKey={appKey}");
                Map<String, String> kv = new HashMap<String, String>();
                if (start != null) {
                    builder.append("&startFinishTime={startFinishTime}");
                    kv.put("startFinishTime", start.getTime() + "");
                }
                if (end != null) {
                    builder.append("&endFinishTime={endFinishTime}");
                    kv.put("endFinishTime", end.getTime() + "");
                }
                builder.append("&allstatus=5");
                if (companyId != null) {
                    builder.append("&companyId={companyId}");
                    kv.put("companyId", String.valueOf(companyId));
                }
                if (lineId != null) {
                    builder.append("&lineId={lineId}");
                    kv.put("lineId", String.valueOf(lineId));
                }
                builder.append("&page={page}");
                kv.put("page", String.valueOf(page));
                builder.append("&rows={rows}");
                kv.put("rows", String.valueOf(rows));

                String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
                List<Order> orderFromSourceVos = null;
                if (null != result) {
                    JSONObject jo = new JSONObject(result);
                    Integer code = jo.getInt("code");
                    if (code == 0) {
                        JSONObject data = jo.getJSONObject("data");
                        JSONArray jsonArray = data.getJSONArray("rows");
                        Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                        orderFromSourceVos = gson
                            .fromJson(jsonArray.toString(), new TypeToken<List<Order>>() {
                            }.getType());
                        if (!CollectionUtils.isEmpty(orderFromSourceVos)) {
                            list.addAll(orderFromSourceVos);
                        }
                    }
                }

                page++;
            }
        }

        return list;
    }

    public List<Car> findCarByLine(Long lineId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_CAR_LINE)
            .append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("lineId", lineId + "");
        builder.append("&lineId={lineId}");

        List<Car> list = new ArrayList<Car>();
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Car>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public boolean isReceiveAnOrder(Long peopleNumber, Integer orderType, Long employId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.ISRECEIVEANORDER).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("employId", employId + "");
        builder.append("&employId={employId}");
        kv.put("orderType", orderType + "");
        builder.append("&orderType={orderType}");
        if (peopleNumber != null) {
            kv.put("peopleNumber", peopleNumber + "");
            builder.append("&peopleNumber={peopleNumber}");
        }

        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                return jo.getBoolean("data");
            }
        }
        return false;
    }

    @Override
    public List<Order> findMonthOrder(Integer year, Integer month) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.ZHUANXIANHEATMAP).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (month != null) {
            builder.append("&month={month}");
            kv.put("month", String.valueOf(month));
        }
        if (year != null) {
            builder.append("&year={year}");
            kv.put("year", String.valueOf(year));
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());

        List<Order> list = new ArrayList<Order>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Object data = jo.get("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void acceptInfoFee(Driver driver, Order order) {

        if (null != driver) {
            Setting setting = settingUtils.get();
            if (setting.getInfoFeeZhuan() != 0) {
                if (null != setting.getInfoFeeType() && setting.getInfoFeeType()
                    .equals(InfoFeeType.acceptTask)) {
                    driver.setVirtual(
                        driver.getVirtual().subtract(new BigDecimal(setting.getInfoFeeZhuan())));
                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                    //扣费记录
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFeeCityline()));
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    driverPaymentsRecord.setOrderId(order.getId());
                    driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANXIAN);
                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                    driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFeeCityline() + "元。");
                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                    //财务记录（保险费）
                    Company mainCompany = companyMapper.selectMainCompany();
                    DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb_f = new StringBuilder();
                    sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);//保险费
                    sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);//对象 服务人员
                    sb_f.append(format_f.format(new Date()));//年月日时间
                    sb_f.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                    financialRecord.setCode(sb_f.toString());
                    financialRecord.setCompanyId(mainCompany.getId());
                    financialRecord.setCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setOrderCompanyId(mainCompany.getId());
                    financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                    financialRecord.setMemo("订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】保险费/信息费");
                    financialRecord.setMoney(new BigDecimal(setting.getInfoFeeZhuan()));
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(driver.getRealname());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANXIAN);
                    financialRecordMapper.insertRecord(financialRecord);
                }
            }

        }

    }

    @Override
    public List<Order> selectCuidan() {
        List<Order> list = new ArrayList<Order>();

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_CUIDAN).append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();

        String result = zhuanxianApi.get(sb.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;
    }

    @Override
    public void closeCuidan(Long orderId) {
        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.CLOSE_CUIDAN).append("?appKey={appKey}");
        sb.append("&orderId={orderId}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("orderId", String.valueOf(orderId));
        zhuanxianApi.put(sb.toString(), kv, settingUtils.get());

    }

    @Override
    public Result<Order> confirmTask(Order order, String xml) {
        Result<Order> result = new Result<Order>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(order.getId()));

        kv.add("realPay", String.valueOf(order.getRealPay()));

        kv.add("guoluMoney", String.valueOf(order.getGuoluMoney()));

        kv.add("yuanchengMoney", String.valueOf(order.getYuanchengMoney()));

        kv.add("otherMoney", String.valueOf(order.getOtherMoney()));

        kv.add("couponMoney", String.valueOf(order.getCouponMoney()));

        if (null != order.getPrePayTypeDetail()) {
            kv.add("prePayTypeDetail", String.valueOf(order.getPrePayTypeDetail()));
        }

        if (null != order.getDiscount()) {
            kv.add("discount", String.valueOf(order.getDiscount()));
        }

        if (null != order.getStartPrice()) {
            kv.add("startPrice", String.valueOf(order.getStartPrice()));
        }

        if (null != order.getMileagePrice()) {
            kv.add("mileagePrice", String.valueOf(order.getMileagePrice()));
        }

        if (null != order.getRunTimePrice()) {
            kv.add("runTimePrice", String.valueOf(order.getRunTimePrice()));
        }

        if (null != order.getWaitPrice()) {
            kv.add("waitPrice", String.valueOf(order.getWaitPrice()));
        }

        kv.add("mileage", String.valueOf(order.getMileage()));

        kv.add("waitTime", String.valueOf(order.getStartWait()));

        kv.add("runTime", String.valueOf(order.getRunTime()));

        if (StringUtils.isNotBlank(xml)) {
            kv.add("xml", xml);
        }

        if (StringUtils.isNotBlank(order.getMemo())) {
            kv.add("memo", order.getMemo());
        }

        if (null != order.getJustKilometres()) {
            kv.add("justKilometres", String.valueOf(order.getJustKilometres()));
        }
        if (null != order.getJustMoney()) {
            kv.add("justMoney", String.valueOf(order.getJustMoney()));
        }

        if (StringUtils.isNotBlank(order.getEndAddress()) && null != order.getEndLng() && null != order.getEndLat()) {
            kv.add("endAddress", order.getEndAddress());

            kv.add("endLat", String.valueOf(order.getEndLat()));

            kv.add("endLng", String.valueOf(order.getEndLng()));
        }

        String resultStr = zhuanxianApi.post(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.CONFIRM_TASK, kv, settingUtils.get());

        logger.info("resultStr:{}", resultStr);
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setSuccess(false);
                result.setMessage(message);
            }
        } else {
            result.setSuccess(false);
            result.setMessage("未知错误");
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result<Order> completeTaskNewV3(Order order, Passenger passenger, Driver driver,
        String completeType, String payType, BigDecimal hasPayed) {

        Result<Order> result = new Result<Order>();
        Double redPacket = order.getRandomRedPacket();
        BigDecimal randomRedPacket = null;
        if (null != redPacket) {
            randomRedPacket = new BigDecimal(order.getRandomRedPacket())
                .setScale(2, BigDecimal.ROUND_HALF_UP);
        }

        boolean ftSuccess = zhuanxianApi.addFinishTime(order.getId(), settingUtils.get()).isSuccess();

        if (order.getStatus().equals(Order.ORDER_STATUS_OK) || !ftSuccess) {
            result.setSuccess(false);
            result.setErrorcode(String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()));
            result.setMessage(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getMessage());
            return result;
        }

        try {
            BigDecimal employProfit = BigDecimal.ZERO;
            BigDecimal companyProfit = BigDecimal.ZERO;

            //优惠券金额
            BigDecimal now_couponMoney = new BigDecimal(order.getCouponMoney() != null ? order.getCouponMoney() : 0);

            //预付费金额
            BigDecimal prePayMoney = new BigDecimal(order.getBudgetPay());
            Double discount = order.getDiscount();
            if (null != discount) {
                prePayMoney = prePayMoney.multiply(new BigDecimal((discount / 10))).setScale(0, BigDecimal.ROUND_UP);
            } else {
                prePayMoney = prePayMoney.subtract(now_couponMoney);
            }

            //结算应支付的金额
            BigDecimal afterPayMoney = BigDecimal.ZERO;
            if (null != order.getPrePayTypeDetail()) {
                if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    afterPayMoney = new BigDecimal(order.getRealPay()).subtract(new BigDecimal(order.getGuoluMoney())).subtract(now_couponMoney);
                    if (afterPayMoney.doubleValue() < 0) {
                        afterPayMoney = BigDecimal.ZERO;
                    }
                    afterPayMoney = afterPayMoney.add(new BigDecimal(order.getGuoluMoney()));
                    afterPayMoney = afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                } else {
                    afterPayMoney = new BigDecimal(order.getRealPay());
                    afterPayMoney = afterPayMoney.subtract(new BigDecimal(order.getGuoluMoney()));
                    afterPayMoney = afterPayMoney.subtract(now_couponMoney);
                    if (afterPayMoney.doubleValue() < 0) {
                        afterPayMoney = BigDecimal.ZERO;
                    }
                    afterPayMoney = afterPayMoney.subtract(prePayMoney);
                    afterPayMoney = afterPayMoney.add(new BigDecimal(order.getGuoluMoney()));

                    if (afterPayMoney.doubleValue() < 0) {
                        afterPayMoney = BigDecimal.ZERO;
                    }

                }
            } else {
                afterPayMoney = new BigDecimal(order.getRealPay());
            }

//            if (null != randomRedPacket) {
//                afterPayMoney = afterPayMoney.subtract(randomRedPacket);
//            }
            //保留两位小数
            afterPayMoney = afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP);

            if ("clickPay".equals(completeType)) {
                if ("helppay".equals(payType)) {//代付支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.helppay);
                    order.setCashMoney(new BigDecimal(order.getCashMoney()).add(afterPayMoney).doubleValue());
                } else if ("sign".equals(payType)) {//签单支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.sign);
                    order.setSignMoney(new BigDecimal(order.getSignMoney()).add(afterPayMoney).doubleValue());
                } else if ("balance".equals(payType)) {//余额支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.balance);
//                    order.setBalanceMoney(new BigDecimal(order.getBalanceMoney()).add(afterPayMoney).doubleValue());
                    //计算使用多少用户余额
                    if(null != randomRedPacket){
                        //如果红包金额大于实际支付金额，不使用账户余额
                        if(order.getRealPay() <= order.getRandomRedPacket()){
                            order.setBalanceMoney(0.0);
                        }
                        else {
//                            afterPayMoney = afterPayMoney.subtract(randomRedPacket);
                            order.setBalanceMoney(new BigDecimal(order.getBalanceMoney()).add(afterPayMoney).subtract(randomRedPacket).doubleValue());
                        }
                    } else {
                        order.setBalanceMoney(new BigDecimal(order.getBalanceMoney()).add(afterPayMoney).doubleValue());
                    }
                }
            }
            else if ("onlinePay".equals(completeType)) {
                if ("alipay".equals(payType)) {//支付宝支付
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.alipay);
                    if(null != randomRedPacket){
                        if(order.getRealPay() <= randomRedPacket.doubleValue()){
                            order.setAlipayMoney(0.0);
                        } else {
                            order.setAlipayMoney(new BigDecimal(order.getAlipayMoney()).add(afterPayMoney).subtract(randomRedPacket).doubleValue());
                        }
                    } else {
                        order.setAlipayMoney(new BigDecimal(order.getAlipayMoney()).add(afterPayMoney).doubleValue());
                    }
                } else if ("weixin".equals(payType)) {
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.weixin);
                    if(null != randomRedPacket){
                        if(order.getRealPay() <= randomRedPacket.doubleValue()){
                            order.setWeixinMoney(0.0);
                        } else {
                            order.setWeixinMoney(new BigDecimal(order.getAlipayMoney()).add(afterPayMoney).subtract(randomRedPacket).doubleValue());
                        }
                    } else {
                        order.setWeixinMoney(new BigDecimal(order.getWeixinMoney()).add(afterPayMoney).doubleValue());
                    }
                } else if ("unionpay".equals(payType)) {
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.unionpay);
                    if(null != randomRedPacket){
                        if(order.getRealPay() <= randomRedPacket.doubleValue()){
                            order.setUnionpayMoney(0.0);
                        } else {
                            order.setUnionpayMoney(new BigDecimal(order.getAlipayMoney()).add(afterPayMoney).subtract(randomRedPacket).doubleValue());
                        }
                    } else {
                        order.setUnionpayMoney(new BigDecimal(order.getUnionpayMoney()).add(afterPayMoney).doubleValue());
                    }
                }
            }
            else if ("clickComplete".equals(completeType)) {
                if (null != order.getPrePayTypeDetail()) {
                    if (order.getPrePayTypeDetail().equals(PayTypeDetails.sign)) {
                        order.setSignMoney(new BigDecimal(order.getRealPay()).doubleValue());
                    } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.balance)) {
                        order.setBalanceMoney(new BigDecimal(order.getRealPay()).doubleValue());
                    } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.alipay)) {
                        order.setAlipayMoney(new BigDecimal(order.getRealPay()).doubleValue());
                    } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.weixin)) {
                        order.setWeixinMoney(new BigDecimal(order.getRealPay()).doubleValue());
                    } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_sign)) {
                        BigDecimal signMoney = new BigDecimal(order.getRealPay()).subtract(new BigDecimal(order.getCouponMoney()));
                        if (signMoney.doubleValue() < 0) {
                            signMoney = BigDecimal.ZERO;
                        }
                        order.setSignMoney(signMoney.doubleValue());
                    } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_balance)) {
                        BigDecimal balanceMoney = new BigDecimal(order.getRealPay()).subtract(new BigDecimal(order.getCouponMoney()));
                        if (balanceMoney.doubleValue() < 0) {
                            balanceMoney = BigDecimal.ZERO;
                        }
                        order.setBalanceMoney(balanceMoney.doubleValue());
                    } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_alipay)) {
                        BigDecimal alipayMoney = new BigDecimal(order.getRealPay()).subtract(new BigDecimal(order.getCouponMoney()));
                        if (alipayMoney.doubleValue() < 0) {
                            alipayMoney = BigDecimal.ZERO;
                        }
                        order.setAlipayMoney(alipayMoney.doubleValue());
                    } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_weixin)) {
                        BigDecimal weixinMoney = new BigDecimal(order.getRealPay()).subtract(new BigDecimal(order.getCouponMoney()));
                        if (weixinMoney.doubleValue() < 0) {
                            weixinMoney = BigDecimal.ZERO;
                        }
                        order.setWeixinMoney(weixinMoney.doubleValue());
                    } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                        order.setAfterPayTypeDetail(Order.PayTypeDetails.helppay);//???
                        order.setCashMoney(BigDecimal.ZERO.doubleValue());
                    }
                }
                else {
                    order.setAfterPayTypeDetail(Order.PayTypeDetails.helppay);
                    order.setCashMoney(BigDecimal.ZERO.doubleValue());
                }
            }

            List<OrderStatus> orderStatuslist = order.getStatusList();
            Date travelDate = null;
            if (!CollectionUtils.isEmpty(orderStatuslist)) {
                Collections.sort(orderStatuslist, new Comparator<OrderStatus>() {
                    public int compare(OrderStatus arg0, OrderStatus arg1) {
                        return arg1.getId().compareTo(arg0.getId());
                    }
                });
                if (!CollectionUtils.isEmpty(orderStatuslist)) {
                    for (OrderStatus orderStatus : orderStatuslist) {
                        if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                            travelDate = orderStatus.getCreated();
                            break;
                        }
                    }
                }
            }

            //客户相关
            if (null != passenger) {
                //实际价格小于或等于预付费
                if ("clickComplete".equals(completeType)) {
                    BigDecimal returnMoney = hasPayed.add(new BigDecimal(order.getCouponMoney())).subtract(new BigDecimal(order.getRealPay()));
                    if (returnMoney.doubleValue() > hasPayed.doubleValue()) {
                        returnMoney = hasPayed;
                    }
                    //如果随机红包不为null，并且红包金额>实际金额，把差价充到用户余额中
                    if(null != order.getRandomRedPacket()){
                        returnMoney = returnMoney.add(new BigDecimal(order.getRandomRedPacket()));
                    }

                    if (returnMoney.doubleValue() != 0) {
                        if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                            passengerApi.createPassengerAccount(passenger, null, returnMoney, PassengerAccount.PayType.RECHARGE_TYPE_RETURN, PassengerAccount.OPERATING_SYS, "订单实际价格小于预付费，返还余额", order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_ZHUANXIAN, null, true, false, settingUtils.get());
                        } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                            Enterprise enterprise = passengerApi.findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
                            if (null != enterprise) {
                                passengerApi.createEnterpriseAccount(enterprise, returnMoney, PassengerAccount.PayType.RECHARGE_TYPE_RETURN, PassengerAccount.OPERATING_SYS, "订单实际价格小于预付费，返还余额", order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_ZHUANXIAN, null, true, false, settingUtils.get());
                            }
                        }
                    }
                }
                else if ("clickPay".equals(completeType)) {
                    if ("helppay".equals(payType)) {//如果是代付，服务人员收到现金，余额减钱
////                        driver.setVirtual(driver.getVirtual().subtract(afterPayMoney));
//
//                        //$$$ 代付扣款
////                        driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
//
////                        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
////                        driverPaymentsRecord.setMoney(afterPayMoney);
////                        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
//                        driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_HELPPAY);
////                        driverPaymentsRecord.setDriverId(driver.getId());
////                        driverPaymentsRecord.setDriverRealName(driver.getRealname());
////                        driverPaymentsRecord.setDriverUserName(driver.getUsername());
////                        driverPaymentsRecord.setDriverPhone(driver.getPhone());
////                        driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
////                        driverPaymentsRecord.setOrderId(order.getId());
////                        driverPaymentsRecord.setOrderNumber(order.getOrderNo());
////                        driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANXIAN);
////                        driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
////                        driverPaymentsRecord.setMemo("为客户【" + passenger.getName() + "】代付" + afterPayMoney + "元。");
////                        driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
////                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
////                        driverPaymentsRecord.setHappend(new Date());
////                        driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);
//
                        HelpPayRecord record = new HelpPayRecord();
                        record.setDriverId(driver.getId());
                        record.setOperateType(HelpPayRecord.DRIVER_HELPPAY);
//                        record.setParam(order.getOrderNo());
                        record.setChangeMoney(afterPayMoney);
                        record.setMemo("司机[" + driver.getId() + "]在订单[" + order.getOrderNo() + "]代付扣款" + afterPayMoney.doubleValue() + "元");
                        record.setTradeNo(order.getOrderNo());
                        helppayService.userDriverMoney(record);
//                    }
                    }
                }

                //常用地址
                if (order.getHasToPlace()) {
                    Result<PassengerAddress> result_address = passengerApi.findPassengerToPlace(passenger.getId(), PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                    PassengerAddress passengerAddress = result_address.getResult();
                    if (null == passengerAddress) {
                        passengerApi.addPassengerToPlace(passenger.getId(), order.getEndAddress(), order.getEndLat(), order.getEndLng(), PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                    } else {
                        passengerApi.updatePassengerToPlace(passenger.getId(), passengerAddress.getId(), order.getEndAddress(), order.getEndLat(), order.getEndLng(), PassengerAddress.TYPE_ADDRESS_OTHER, settingUtils.get());
                    }
                }

                //结算记录
                if ("clickPay".equals(completeType) || "onlinePay".equals(completeType)) {

                    String memo = "";
                    PassengerAccount.PayType ptype = null;
                    //结算费用
                    BigDecimal settleAccounts = afterPayMoney;
                    //操作账户余额
                    BigDecimal yue = afterPayMoney;
                    if(null != randomRedPacket){
                        if("balance".equals(payType) || "onlinePay".equals(completeType)) {
                            if (afterPayMoney.doubleValue() < randomRedPacket.doubleValue()) {
                                memo += "使用了" + afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP) + "元随机红包；";
                                memo += "红包剩余" + randomRedPacket.subtract(afterPayMoney).setScale(2, BigDecimal.ROUND_HALF_UP) + "返还余额；";
                                settleAccounts = BigDecimal.ZERO;
                                //是负数为账户充值
                                yue = afterPayMoney.subtract(randomRedPacket);
                            } else {
                                settleAccounts = afterPayMoney.subtract(randomRedPacket).setScale(2, BigDecimal.ROUND_HALF_UP);
                                memo += "使用了" + randomRedPacket.setScale(2, BigDecimal.ROUND_HALF_UP) + "元随机红包；";
                                //正数为账户扣费
                                yue = afterPayMoney.subtract(randomRedPacket).setScale(2, BigDecimal.ROUND_HALF_UP);
                            }
                        }

                    }

                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.helppay)) {
                        memo += "结算使用代付" + afterPayMoney.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_CASH;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)) {
                        memo += "结算使用签单支付" + afterPayMoney.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_SIGN;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                        memo += "结算使用余额支付" + settleAccounts.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_BALANCE;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.alipay)) {
                        memo += "结算使用支付宝支付" + settleAccounts.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_ALIPAY;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.weixin)) {
                        memo += "结算使用微信支付" + settleAccounts.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_WEIXIN;
                    }
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.unionpay)) {
                        memo += "结算使用银联支付" + settleAccounts.toString() + "元。";
                        ptype = PassengerAccount.PayType.PAYTYPE_UNIONPAY;
                    }

                    //是否更新余额
                    boolean updateBlance = false;
                    if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign) || order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                        updateBlance = true;
                    }

                    PassengerAccount passengerAccount = null;

                    if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {

                        Result<PassengerAccount> result_account = passengerApi.createPassengerAccount(passenger, null, yue.negate(), ptype, PassengerAccount.OPERATING_SYS, memo, order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_ZHUANXIAN, null, updateBlance, true, settingUtils.get());
                        passengerAccount = result_account.getResult();
                    } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                        Enterprise enterprise = passengerApi.findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
                        if (null != enterprise) {
                            Result<PassengerAccount> result_account = passengerApi.createEnterpriseAccount(enterprise, yue.negate(), ptype, PassengerAccount.OPERATING_SYS, memo, order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_ZHUANXIAN, null, updateBlance, true, settingUtils.get());
                            passengerAccount = result_account.getResult();
                        }
                    }

                    if (updateBlance) {
                        //客户扣费短信
                        if (null != passengerAccount) {
                            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                                MemberConsumedEvent consumedEvent = new MemberConsumedEvent(passengerAccount, null);
                                applicationEventMulticaster.multicastEvent(consumedEvent);
                            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                                MemberConsumedEvent consumedEvent = new MemberConsumedEvent(passengerAccount, passenger.getPhone());
                                applicationEventMulticaster.multicastEvent(consumedEvent);
                            }
                        }
                    }

                }

                passenger.setMileage(passenger.getMileage() + order.getMileage());
                passenger.setDrivingNumberTimes(passenger.getDrivingNumberTimes() + 1);
                passengerApi.updatePersonal(passenger, settingUtils.get());

                if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi.findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
                    if (null != enterprise) {
                        enterprise.setDrivingNumberTimes(enterprise.getDrivingNumberTimes() + 1);
                        passengerApi.updateEnterpriseInfo(enterprise, settingUtils.get());
                    }
                }

                BigDecimal receiptMoney = new BigDecimal(order.getRealPay()).subtract(new BigDecimal(order.getGuoluMoney())).subtract(new BigDecimal(order.getCouponMoney()));
                if (receiptMoney.doubleValue() > 0) {
                    passengerApi.createReceipt(passenger, receiptMoney.negate(), settingUtils.get());
                }

            }

//            BigDecimal realCash = new BigDecimal(order.getRealPay()).subtract(new BigDecimal(order.getGuoluMoney()));
            BigDecimal realCash = new BigDecimal(order.getRealPay());

            //优惠劵是否参与提成
            Setting setting = settingUtils.get();
            boolean couponTicheng = setting.isCouponTicheng();

            //是否使用了优惠劵
            if (order.getCouponMoney().doubleValue() > 0) {
                if (!couponTicheng) {
                    realCash = realCash.subtract(new BigDecimal(order.getCouponMoney()));
                    if (realCash.compareTo(BigDecimal.ZERO) == -1) {
                        realCash = BigDecimal.ZERO;
                    }
                }
            }

            //服务人员设为空闲
            boolean companyGetAll = false;//公司是否的全部

            DateFormat format = new SimpleDateFormat("yyyyMMdd");

            StringBuilder sbmemo = new StringBuilder();
            sbmemo.append("订单【" + order.getOrderNo() + "】，客户【" + order.getPassengerName() + "(" + order.getPassengerPhone() + ")】，");

            //预支付备注
            if (null != order.getPrePayTypeDetail()) {
                if (order.getPrePayTypeDetail().equals(PayTypeDetails.sign)) {
                    sbmemo.append("预付费：签单支付（" + prePayMoney + "元）。");
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.balance)) {
                    sbmemo.append("预付费：余额支付（" + prePayMoney + "元）。");
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.alipay)) {
                    sbmemo.append("预付费：支付宝支付（" + prePayMoney + "元）。");
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.weixin)) {
                    sbmemo.append("预付费：微信支付（" + prePayMoney + "元）。");
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.unionpay)) {
                    sbmemo.append("预付费：银联支付（" + prePayMoney + "元）。");
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_sign)) {
                    if (null == discount) {
                        sbmemo.append("预付费：签单支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString() + "元优惠券。");
                    } else {
                        sbmemo.append("预付费：签单支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                    }
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_balance)) {
                    if (null == discount) {
                        sbmemo.append("预付费：余额支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString() + "元优惠券。");
                    } else {
                        sbmemo.append("预付费：余额支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                    }
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_alipay)) {
                    if (null == discount) {
                        sbmemo.append("预付费：支付宝支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString() + "元优惠券。");
                    } else {
                        sbmemo.append("预付费：支付宝支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                    }
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_weixin)) {
                    if (null == discount) {
                        sbmemo.append("预付费：微信支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString() + "元优惠券。");
                    } else {
                        sbmemo.append("预付费：微信支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                    }
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon_unionpay)) {
                    if (null == discount) {
                        sbmemo.append("预付费：银联支付（" + prePayMoney + "元）,并且使用了" + order.getCouponMoney().toString() + "元优惠券。");
                    } else {
                        sbmemo.append("预付费：银联支付（" + prePayMoney + "元）,并且使用了" + discount.toString() + "折优惠券。");
                    }
                } else if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    if (null == discount) {
                        sbmemo.append("使用了" + order.getCouponMoney().toString() + "元优惠券。");
                    } else {
                        sbmemo.append("使用了" + discount.toString() + "折优惠券。");
                    }
                }

                if (couponTicheng) {
                    sbmemo.append("优惠劵参与提成计算。");
                } else {
                    sbmemo.append("优惠劵不参与提成计算。");
                }

            }

            //后支付备注
            if (null != order.getAfterPayTypeDetail()) {
                //计算结算金额
                BigDecimal settleAccounts = afterPayMoney;
                if(null != randomRedPacket){
                    if("balance".equals(payType) || "onlinePay".equals(completeType)) {
                        if (afterPayMoney.doubleValue() <= randomRedPacket.doubleValue()) {
                            sbmemo.append("使用了" + afterPayMoney.setScale(2, BigDecimal.ROUND_HALF_UP) + "元随机红包。");
                            //实际费用小于红包金额，全额使用红包
                            settleAccounts = BigDecimal.ZERO;
                        } else {
                            sbmemo.append("使用了" + order.getRandomRedPacket() + "元随机红包。");
                            settleAccounts = afterPayMoney.subtract(randomRedPacket).setScale(2, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                }
                if (order.getAfterPayTypeDetail().equals(PayTypeDetails.helppay)) {
                    sbmemo.append("结算加收：代付（" + afterPayMoney + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.sign)) {
                    sbmemo.append("结算加收：签单支付（" + afterPayMoney + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.balance)) {
                    sbmemo.append("结算加收：余额支付（" + settleAccounts + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.alipay)) {
                    sbmemo.append("结算加收：支付宝支付（" + settleAccounts + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.weixin)) {
                    sbmemo.append("结算加收：微信支付（" + settleAccounts + "元）。");
                } else if (order.getAfterPayTypeDetail().equals(PayTypeDetails.unionpay)) {
                    sbmemo.append("结算加收：银联支付（" + settleAccounts + "元）。");
                }
            }

            if (null != driver) {
                List<Order> activedList = this.findActivedOrdersByDriver(driver.getId());
                if (!CollectionUtils.isEmpty(activedList)) {
                    long pai = 0;
                    long jie = 0;
                    long busy = 0;
                    for (Order activedOrder : activedList) {
                        if (!activedOrder.getId().equals(order.getId())) {
                            if (activedOrder.getStatus().equals(Order.ORDER_STATUS_PAIDAN)) {
                                ++pai;
                            } else if (activedOrder.getStatus().equals(Order.ORDER_STATUS_JIEDAN)) {
                                ++jie;
                            } else if (activedOrder.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                                ++busy;
                            }
                        }
                    }
                    if (busy > 0 || jie > 0) {
                        driver.setStatus(Driver.DRIVER_BUSY);
                    } else if (pai > 0) {
                        driver.setStatus(Driver.DRIVER_APPLY_ORDER);
                    } else {
                        driver.setStatus(Driver.DRIVER_ONLINE);
                    }
                    driver.setTodayOrders(driver.getTodayOrders() + 1);
                    driver.setMonthOrders(driver.getMonthOrders() + 1);
                    driver.setDriveTimes(driver.getDriveTimes() + 1);
                    driverMapper.updateWhenFinishOrderByKey(driver);
                }

                //$$$ 公司扣费提成|抽成
                //兼职司机
                if (null != driver.getType() && Driver.DRIVER_TYPR_PARTTIME.equals(driver.getType())) {

//	                    DriverChoseLevelCar driverChoseLevelCar = driverChoseLevelCarMapper.selectByDriverAndCompany(driver.getId(), order.getCompanyId());
                    Integer lineType = DriverChoseLevelZhuanxian.TYPE_PINCHE;
                    if (order.getOrderType().equals(Order.TYPE_PINCHE)) {
                        lineType = DriverChoseLevelZhuanxian.TYPE_PINCHE;
                    } else if (order.getOrderType().equals(Order.TYPE_BAOCHE)) {
                        lineType = DriverChoseLevelZhuanxian.TYPE_BAOCHE;
                    } else if (order.getOrderType().equals(Order.TYPE_JIHUO)) {
                        lineType = DriverChoseLevelZhuanxian.TYPE_JIHUO;
                    }

                    DriverChoseLevelZhuanxian driverChoseLevelZhuanxian = driverChoseLevelZhuanxianMapper.selectByDriverAndLine(driver.getId(), null, lineType);
                    if (null != driverChoseLevelZhuanxian) {

                        DriverLevel driverLevel = driverLevelMapper.selectByPrimaryKey(driverChoseLevelZhuanxian.getDriverlevelId());

//	                        if (driverChoseLevelZhuanxian.getDriverlevelId() == 0) {//始终使用本公司提成
//	                            DriverChoseLevelCar driverChoseLevelCar2 = driverChoseLevelCarMapper.selectByDriverAndCompany(driver.getId(), driver.getCompanyId());
//	                            if (null != driverChoseLevelCar2) {
//	                                driverLevel = driverLevelMapper.selectByPrimaryKey(driverChoseLevelCar2.getDriverlevelId());
//	                            }
//	                        } else {
//	                            driverLevel = driverLevelMapper.selectByPrimaryKey(driverChoseLevelZhuanxian.getDriverlevelId());
//	                        }

                        DriverLevelDetail detail = null;
                        DriverLevelMoneyTimeDetail moneyTimeDetail = null;

                        if (null != driverLevel) {
                            if (driverLevel.getType().equals(0)) {
                                driverLevel.setDriverLevelDetails(driverLevelDetailMapper.selectByDriverLevel(driverLevel.getId()));
                                if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                    detail = driverLevel.getDeatil(order.getServerTime());
                                } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                                    detail = driverLevel.getDeatil(travelDate);
                                } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                                    detail = driverLevel.getDeatil(new Date());
                                }
                            } else if (driverLevel.getType().equals(1)) {
                                driverLevel.setDriverLevelMoneyTimeDetails(driverLevelMoneyTimeDetailMapper.selectByDriverLevel(driverLevel.getId()));
                                if (driverLevel.getTimePoint().equals(TimePoint.serviceTime)) {
                                    moneyTimeDetail = driverLevel.getMoneyTimeDeatil(order.getServerTime());
                                } else if (driverLevel.getTimePoint().equals(TimePoint.startDrive)) {
                                    moneyTimeDetail = driverLevel.getMoneyTimeDeatil(travelDate);
                                } else if (driverLevel.getTimePoint().equals(TimePoint.finishTime)) {
                                    moneyTimeDetail = driverLevel.getMoneyTimeDeatil(new Date());
                                }
                            }
                        }

                        if (null != detail) {

                            BigDecimal money = BigDecimal.ZERO;
                            BigDecimal companyMoney = BigDecimal.ZERO;

                            if (detail.getDriverLevelType().equals(DriverLevelType.ticheng)) {
                                if (realCash.compareTo(detail.getMinCommission()) == -1) {
                                    money = realCash.subtract(detail.getLowCommission()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    companyMoney = detail.getLowCommission();
                                    if (money.doubleValue() < 0) {
                                        money = BigDecimal.ZERO;
                                        companyMoney = realCash;
                                    }
                                    sbmemo.append("按照【低于" + detail.getMinCommission() + "元公司得" + detail.getLowCommission() + "元】方式，服务人员得" + money + "元。");
                                } else {
                                    money = realCash.multiply(new BigDecimal(100).subtract(detail.getCommission())).divide(new BigDecimal(100));
                                    companyMoney = realCash.subtract(money);
                                    sbmemo.append("按照【" + detail.getCommission() + "%公司所得】提成方式。");
                                }
                            }
                            else if (detail.getDriverLevelType().equals(DriverLevelType.guding)) {
                                if (realCash.compareTo(detail.getMinMoney()) == -1) {
                                    money = realCash.subtract(detail.getLowMoney()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    companyMoney = detail.getLowMoney();
                                    if (money.doubleValue() < 0) {
                                        money = BigDecimal.ZERO;
                                        companyMoney = realCash;
                                    }
                                    sbmemo.append("按照【低于" + detail.getMinMoney() + "元公司得" + detail.getLowMoney() + "元】方式，服务人员得" + money + "元。");
                                } else {

                                    sbmemo.append("按照【" + detail.getMoney() + "元公司所得】提成方式。");

                                    if (realCash.compareTo(detail.getMoney()) == -1) {
                                        money = BigDecimal.ZERO;
                                        companyMoney = realCash;
                                    } else {
                                        money = realCash.subtract(detail.getMoney());
                                        companyMoney = detail.getMoney();
                                    }

                                }
                            }

                            employProfit = money;
                            companyProfit = companyMoney;

                            driver.setVirtual(driver.getVirtual().add(money));
                            driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                            driverPaymentsRecord.setMoney(money);
                            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                            driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                            driverPaymentsRecord.setDriverId(driver.getId());
                            driverPaymentsRecord.setDriverRealName(driver.getRealname());
                            driverPaymentsRecord.setDriverUserName(driver.getUsername());
                            driverPaymentsRecord.setDriverPhone(driver.getPhone());
                            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                            driverPaymentsRecord.setOrderId(order.getId());
                            driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                            driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANXIAN);
                            driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                            driverPaymentsRecord.setMemo(sbmemo.toString());
                            driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                            driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                            driverPaymentsRecord.setHappend(new Date());
                            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                            //公司财务
                            String companyMemo = "订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】收入。";

                            Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
                            Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());

                            FinancialRecord financialRecord = new FinancialRecord();
                            StringBuilder sb = new StringBuilder();
                            sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                            sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                            sb.append(format.format(new Date()));//年月日时间
                            sb.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                            financialRecord.setCode(sb.toString());
                            financialRecord.setCompanyId(company.getId());
                            financialRecord.setCompanyName(company.getAbbreviation());
                            financialRecord.setOrderCompanyId(orderCompany.getId());
                            financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                            financialRecord.setMemo(companyMemo + driverPaymentsRecord.getMemo());
                            financialRecord.setMoney(companyMoney);
                            financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                            financialRecord.setWho(order.getPassengerName());
                            financialRecord.setOrderId(order.getId());
                            financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                            financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANXIAN);
                            financialRecordMapper.insertRecord(financialRecord);

                            if("balance".equals(payType) || "onlinePay".equals(completeType)) {
                                if (null != randomRedPacket) {
                                    String companyPayMemo = "订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】支出。";
                                    BigDecimal usedRedPacket = afterPayMoney;
                                    if (afterPayMoney.doubleValue() > randomRedPacket.doubleValue()) {
                                        usedRedPacket = randomRedPacket;
                                    }
                                    String detailMemo = "客户【" + order.getPassengerName() + "(" + order.getPassengerPhone() + ")】，领取了" + randomRedPacket + "元随机红包，使用了" + usedRedPacket + "元随机红包";
                                    if (randomRedPacket.doubleValue() > afterPayMoney.doubleValue()) {
                                        BigDecimal surplus = randomRedPacket.subtract(afterPayMoney);
                                        detailMemo += "，剩余" + surplus + "元返还余额。";
                                    } else {
                                        detailMemo += "。";
                                    }
                                    StringBuilder sb2 = new StringBuilder();
                                    sb2.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                                    sb2.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                                    sb2.append(format.format(new Date()));//年月日时间 0201201907150036
                                    sb2.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                                    financialRecord.setCode(null);
                                    financialRecord.setCode(sb2.toString());
                                    financialRecord.setMemo(companyPayMemo + detailMemo);
                                    BigDecimal surplus = usedRedPacket;
                                    if (randomRedPacket.doubleValue() > afterPayMoney.doubleValue()) surplus = randomRedPacket;
                                    financialRecord.setMoney(surplus.negate());
                                    financialRecordMapper.insertRecord(financialRecord);
                                }
                            }

                        }
                        else if (null != moneyTimeDetail) {//复杂提成

                            BigDecimal money = BigDecimal.ZERO;
                            BigDecimal companyMoney = BigDecimal.ZERO;//公司所得金额

                            if (!CollectionUtils.isEmpty(moneyTimeDetail.getDriverLevelMoneyDetails())) {

                                for (DriverLevelMoneyDetail dlmd : moneyTimeDetail.getDriverLevelMoneyDetails()) {
                                    if (realCash.doubleValue() >= dlmd.getFromMoney().doubleValue()) {

                                        BigDecimal _money = BigDecimal.ZERO;
                                        if (realCash.doubleValue() >= dlmd.getToMoney().doubleValue()) {
                                            _money = dlmd.getToMoney().subtract(dlmd.getFromMoney());
                                        } else {
                                            _money = realCash.subtract(dlmd.getFromMoney());
                                        }

                                        if (dlmd.getDriverLevelMoneyType().equals(DriverLevelMoneyType.guding)) {//固定
                                            BigDecimal tcMoney = dlmd.getMoney().multiply(new BigDecimal((int) (_money.doubleValue() / dlmd.getMoneyUnit().doubleValue())));
                                            companyMoney = companyMoney.add(tcMoney);
                                        } else if (dlmd.getDriverLevelMoneyType().equals(DriverLevelMoneyType.ticheng)) {//比例
                                            BigDecimal tcMoney = _money.multiply(dlmd.getCommission()).divide(new BigDecimal(100));
                                            companyMoney = companyMoney.add(tcMoney);
                                        }
                                    }
                                }
                            }

                            if (realCash.compareTo(companyMoney) == -1) {
                                companyMoney = realCash;
                                money = BigDecimal.ZERO;
                                sbmemo.append("金额不足，公司实际提成" + companyMoney + "元。");
                            } else {
                                money = realCash.subtract(companyMoney);
                            }

                            employProfit = money;
                            companyProfit = companyMoney;

                            driver.setVirtual(driver.getVirtual().add(money));
                            driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

                            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                            driverPaymentsRecord.setMoney(money);
                            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                            driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER);
                            driverPaymentsRecord.setDriverId(driver.getId());
                            driverPaymentsRecord.setDriverRealName(driver.getRealname());
                            driverPaymentsRecord.setDriverUserName(driver.getUsername());
                            driverPaymentsRecord.setDriverPhone(driver.getPhone());
                            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                            driverPaymentsRecord.setOrderId(order.getId());
                            driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                            driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANXIAN);
                            driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                            driverPaymentsRecord.setMemo(sbmemo.toString());
                            driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                            driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                            driverPaymentsRecord.setHappend(new Date());
                            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                            //公司财务
                            String companyMemo = "订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】收入。";

                            Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
                            Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());

                            FinancialRecord financialRecord = new FinancialRecord();
                            StringBuilder sb = new StringBuilder();
                            sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                            sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                            sb.append(format.format(new Date()));//年月日时间
                            sb.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                            financialRecord.setCode(sb.toString());
                            financialRecord.setCompanyId(company.getId());
                            financialRecord.setCompanyName(company.getAbbreviation());
                            financialRecord.setOrderCompanyId(orderCompany.getId());
                            financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                            financialRecord.setMemo(companyMemo + driverPaymentsRecord.getMemo());
                            financialRecord.setMoney(companyMoney);
                            financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                            financialRecord.setWho(order.getPassengerName());
                            financialRecord.setOrderId(order.getId());
                            financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                            financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANXIAN);
                            financialRecordMapper.insertRecord(financialRecord);

                            if("balance".equals(payType) || "onlinePay".equals(completeType)) {
                                if (null != randomRedPacket) {
                                    String companyPayMemo = "订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】支出。";
                                    BigDecimal usedRedPacket = afterPayMoney;
                                    if (afterPayMoney.doubleValue() > randomRedPacket.doubleValue()) {
                                        usedRedPacket = randomRedPacket;
                                    }
                                    String detailMemo = "客户【" + order.getPassengerName() + "(" + order.getPassengerPhone() + ")】，领取了" + randomRedPacket + "元随机红包，使用了" + usedRedPacket + "元随机红包";
                                    if (randomRedPacket.doubleValue() > afterPayMoney.doubleValue()) {
                                        BigDecimal surplus = randomRedPacket.subtract(afterPayMoney);
                                        detailMemo += "，剩余" + surplus + "元返还余额。";
                                    } else {
                                        detailMemo += "。";
                                    }
                                    StringBuilder sb2 = new StringBuilder();
                                    sb2.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                                    sb2.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                                    sb2.append(format.format(new Date()));//年月日时间 0201201907150036
                                    sb2.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                                    financialRecord.setCode(null);
                                    financialRecord.setCode(sb2.toString());
                                    financialRecord.setMemo(companyPayMemo + detailMemo);
                                    BigDecimal surplus = usedRedPacket;
                                    if (randomRedPacket.doubleValue() > afterPayMoney.doubleValue()) surplus = randomRedPacket;
                                    financialRecord.setMoney(surplus.negate());
                                    financialRecordMapper.insertRecord(financialRecord);
                                }
                            }

                        }
                        else {
                            companyGetAll = true;
                        }

                    } else {
                        companyGetAll = true;
                    }
                }
                //全职司机
                else {
                    companyGetAll = true;
                }

                //公司得全部
                if (companyGetAll) {

                    companyProfit = realCash;

                    String companyMemo = "订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】收入。";

                    Company company = companyMapper.selectByPrimaryKey(driver.getCompanyId());
                    Company orderCompany = companyMapper.selectByPrimaryKey(order.getCompanyId());

                    FinancialRecord financialRecord = new FinancialRecord();
                    StringBuilder sb = new StringBuilder();
                    sb.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                    sb.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                    sb.append(format.format(new Date()));//年月日时间 0201201907150036
                    sb.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                    financialRecord.setCode(sb.toString());
                    financialRecord.setCompanyId(company.getId());
                    financialRecord.setCompanyName(company.getAbbreviation());
                    financialRecord.setOrderCompanyId(orderCompany.getId());
                    financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());
                    financialRecord.setMemo(companyMemo + sbmemo.toString());
                    financialRecord.setMoney(realCash);
                    financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                    financialRecord.setWho(order.getPassengerName());
                    financialRecord.setOrderId(order.getId());
                    financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_SHOURU);
                    financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANXIAN);
                    financialRecordMapper.insertRecord(financialRecord);

                    //如果有随机红包，增加一条公司财务支出记录
                    //
                    if("balance".equals(payType) || "onlinePay".equals(completeType)) {
                        if (null != randomRedPacket) {
                            String companyPayMemo = "订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】支出。";
                            BigDecimal usedRedPacket = afterPayMoney;
                            if (afterPayMoney.doubleValue() > randomRedPacket.doubleValue()) {
                                usedRedPacket = randomRedPacket;
                            }
                            String detailMemo = "客户【" + order.getPassengerName() + "(" + order.getPassengerPhone() + ")】，领取了" + randomRedPacket + "元随机红包，使用了" + usedRedPacket + "元随机红包";
                            if (randomRedPacket.doubleValue() > afterPayMoney.doubleValue()) {
                                BigDecimal surplus = randomRedPacket.subtract(afterPayMoney);
                                detailMemo += "，剩余" + surplus + "元返还余额。";
                            } else {
                                detailMemo += "。";
                            }
                            StringBuilder sb2 = new StringBuilder();
                            sb2.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                            sb2.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                            sb2.append(format.format(new Date()));//年月日时间 0201201907150036
                            sb2.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                            financialRecord.setCode(null);
                            financialRecord.setCode(sb2.toString());
                            financialRecord.setMemo(companyPayMemo + detailMemo);
                            BigDecimal surplus = usedRedPacket;
                            if (randomRedPacket.doubleValue() > afterPayMoney.doubleValue()) surplus = randomRedPacket;
                            financialRecord.setMoney(surplus.negate());
                            financialRecordMapper.insertRecord(financialRecord);
                        }
                    }
                }

            }


            if (null != driver) {
                //过路费
//                BigDecimal fee = new BigDecimal(order.getGuoluMoney());
//                if (fee.doubleValue() > 0) {
//                    driver.setVirtual(driver.getVirtual().add(fee));
//                    driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
//
//                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
//                    driverPaymentsRecord.setMoney(fee);
//                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
//                    driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ORDER_GUOLU);
//                    driverPaymentsRecord.setDriverId(driver.getId());
//                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
//                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
//                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
//                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
//                    driverPaymentsRecord.setOrderId(order.getId());
//                    driverPaymentsRecord.setOrderNumber(order.getOrderNo());
//                    driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANXIAN);
//                    driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
//                    driverPaymentsRecord.setMemo("订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】过路费");
//                    driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
//                    driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
//                    driverPaymentsRecord.setHappend(new Date());
//                    driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);
//
//                }
                //保险费、信息费不为零
                if (setting.getInfoFeeCityline() != 0) {
                    if (null != setting.getInfoFeeType() && setting.getInfoFeeType()
                        .equals(InfoFeeType.finishTask)) {
                        driver.setVirtual(driver.getVirtual()
                            .subtract(new BigDecimal(setting.getInfoFeeCityline())));
                        driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());
                        //扣费记录
                        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                        driverPaymentsRecord.setMoney(new BigDecimal(setting.getInfoFeeCityline()));
                        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                        driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMEDRECORD_TYPE_XINXI);
                        driverPaymentsRecord.setDriverId(driver.getId());
                        driverPaymentsRecord.setDriverRealName(driver.getRealname());
                        driverPaymentsRecord.setDriverUserName(driver.getUsername());
                        driverPaymentsRecord.setDriverPhone(driver.getPhone());
                        driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                        driverPaymentsRecord.setOrderId(order.getId());
                        driverPaymentsRecord.setOrderNumber(order.getOrderNo());
                        driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANXIAN);
                        driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
                        driverPaymentsRecord.setMemo("扣除公司所得保险费/信息费" + setting.getInfoFeeCityline() + "元。");
                        driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                        driverPaymentsRecord.setHappend(new Date());
                        driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

                        //财务记录（保险费）
                        Company mainCompany = companyMapper.selectMainCompany();
                        DateFormat format_f = new SimpleDateFormat("yyyyMMdd");
                        FinancialRecord financialRecord = new FinancialRecord();
                        StringBuilder sb_f = new StringBuilder();
                        sb_f.append(OrderNumberConfig.FINANCIAL_XINXI);//保险费
                        sb_f.append(OrderNumberConfig.FINANCIAL_WHO_DRIVER);//对象 服务人员
                        sb_f.append(format_f.format(new Date()));//年月日时间
                        sb_f.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                        financialRecord.setCode(sb_f.toString());
                        financialRecord.setCompanyId(mainCompany.getId());
                        financialRecord.setCompanyName(mainCompany.getAbbreviation());
                        financialRecord.setOrderCompanyId(mainCompany.getId());
                        financialRecord.setOrderCompanyName(mainCompany.getAbbreviation());
                        financialRecord.setMemo("订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】保险费/信息费");
                        financialRecord.setMoney(new BigDecimal(setting.getInfoFeeCityline()));
                        financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
                        financialRecord.setWho(driver.getRealname());
                        financialRecord.setOrderId(order.getId());
                        financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_XINXI);
                        financialRecord.setOrderType(FinancialRecord.ORDER_TYPE_ZHUANXIAN);
                        financialRecordMapper.insertRecord(financialRecord);

                        if("balance".equals(payType) || "onlinePay".equals(completeType)) {
                            if (null != randomRedPacket) {
                                String companyPayMemo = "订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】支出。";
                                BigDecimal usedRedPacket = afterPayMoney;
                                if (afterPayMoney.doubleValue() > randomRedPacket.doubleValue()) {
                                    usedRedPacket = randomRedPacket;
                                }
                                String detailMemo = "客户【" + order.getPassengerName() + "(" + order.getPassengerPhone() + ")】，领取了" + randomRedPacket + "元随机红包，使用了" + usedRedPacket + "元随机红包";
                                if (randomRedPacket.doubleValue() > afterPayMoney.doubleValue()) {
                                    BigDecimal surplus = randomRedPacket.subtract(afterPayMoney);
                                    detailMemo += "，剩余" + surplus + "元返还余额。";
                                } else {
                                    detailMemo += "。";
                                }
                                StringBuilder sb2 = new StringBuilder();
                                sb2.append(OrderNumberConfig.FINANCIAL_ORDER);//订单金额
                                sb2.append(OrderNumberConfig.FINANCIAL_WHO_MEMBER);//对象 客户
                                sb2.append(format.format(new Date()));//年月日时间 0201201907150036
                                sb2.append(OrderNumberConfig.padZero(financialRecordMapper.getRunningNumber() + 1));//流水号
                                financialRecord.setCode(null);
                                financialRecord.setCode(sb2.toString());
                                financialRecord.setMemo(companyPayMemo + detailMemo);
                                BigDecimal surplus = usedRedPacket;
                                if (randomRedPacket.doubleValue() > afterPayMoney.doubleValue()) surplus = randomRedPacket;
                                financialRecord.setMoney(surplus.negate());
                                financialRecordMapper.insertRecord(financialRecord);
                            }
                        }

                    }
                }

            }

            //更新订单
            MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

            kv.add("orderId", String.valueOf(order.getId()));

            if (null != order.getAfterPayTypeDetail()) {
                kv.add("afterPayTypeDetail", order.getAfterPayTypeDetail().toString());
            }
            kv.add("cashMoney", new BigDecimal(order.getCashMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            kv.add("signMoney", new BigDecimal(order.getSignMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            kv.add("balanceMoney", new BigDecimal(order.getBalanceMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            kv.add("alipayMoney", new BigDecimal(order.getAlipayMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            kv.add("weixinMoney", new BigDecimal(order.getWeixinMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            if (null != order.getUnionpayMoney()) {
                kv.add("unionpayMoney", new BigDecimal(order.getUnionpayMoney()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }

            kv.add("companyProfit", companyProfit.toString());

            kv.add("employProfit", employProfit.toString());

            String resultStr = zhuanxianApi.post(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.FINISH_TASK, kv, settingUtils.get());
            if (StringUtils.isNotBlank(resultStr)) {
                JSONObject jo = new JSONObject(resultStr);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    //结算成功保存首单免费客户信息
                    FirstOrderPassenger firstOrderPassenger = new FirstOrderPassenger();
                    firstOrderPassenger.setPassengerId(passenger.getId());
                    firstOrderPassenger.setType(FirstOrderPassenger.FREE_ORDERTYPE_ZHUANXIAN);
                    firstOrderPassengerMapper.insertRecord(firstOrderPassenger);


                    result.setSuccess(true);
                    ReactorVo rVo = new ReactorVo();
                    rVo.setOrderChannelName(order.getChannelName());
                    rVo.setOrderType(OrderType.zhuanxian);
                    rVo.setPassenger(passenger);
                    rVo.setActivityEvent(ActivityEvent.orderCompleteTimes);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);
                    //结算短信
                    ZhuanxianOrderFinishEvent zhuanOrderFinishEvent = new ZhuanxianOrderFinishEvent(order);
                    IntroduceRebateEvent introduce_rebate_event = new IntroduceRebateEvent(passenger, order, new BigDecimal(order.getRealPay()), 1);
                    applicationEventMulticaster.multicastEvent(introduce_rebate_event);
                    applicationEventMulticaster.multicastEvent(zhuanOrderFinishEvent);
                } else {
                    String message = jo.getString("message");
                    result.setSuccess(false);
                    result.setMessage(message);
                }
            } else {
                result.setSuccess(false);
                result.setMessage("内部服务器错误");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("内部服务器错误");
        }

        return result;
        /*return null;*/

    }

    @Override
    public Result<PayRecordOrder> createPayRecordOrder(PayRecordOrder payRecordOrder) {

        Result<PayRecordOrder> result = new Result<PayRecordOrder>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("orderId", String.valueOf(payRecordOrder.getOrderId()));

        kv.add("money", payRecordOrder.getMoney().toString());

        kv.add("payRecordTypeOrder", payRecordOrder.getPayRecordTypeOrder().toString());

        String resultStr = zhuanxianApi.post(zhuanxianApi.getZhuanxianBaseURL() + ZhuanxianApi.CREATE_PAYRECORDORDER, kv, settingUtils.get());
        if (null != resultStr) {
            JSONObject jo = new JSONObject(resultStr);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                PayRecordOrder pr = gson.fromJson(data.toString(), PayRecordOrder.class);
                result.setResult(pr);
                result.setSuccess(true);
            } else {
                String message = jo.getString("message");
                result.setSuccess(false);
                result.setMessage(message);
            }
        } else {
            result.setSuccess(false);
            result.setMessage("未知错误");
        }

        return result;
    }

    @Override
    public PayRecordOrder findOnePayRecordOrder(Long orderId) {
        PayRecordOrder payRecordOrder = null;
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_PAYRECORDORDER_ONE).append("?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(orderId));
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                payRecordOrder = gson.fromJson(data.toString(), PayRecordOrder.class);
            }
        }
        return payRecordOrder;
    }

    @Override
    public Result<PayRecordOrder> payRecordOrderTreatment(PayRecordOrder payRecordOrder) {
        Result<PayRecordOrder> result = new Result<PayRecordOrder>();

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.TREATMENT_PAYRECORDORDER).append("?id={id}&appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(payRecordOrder.getId()));

        String resultStr = zhuanxianApi.put(sb.toString(), kv, settingUtils.get());
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jo = new JSONObject(resultStr);
            String message = jo.getString("message");
            result.setMessage(message);
            result.setSuccess(false);
        } else {
            result.setSuccess(true);
        }

        return result;
    }

    @Override
    public List<Order> queryByEmployId(Long employId, String status) {

        Map<String, String> kv = new HashMap<String, String>();

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL());
        builder.append(ZhuanxianApi.FIND_MYWORK);
        builder.append("?appKey={appKey}&employId={employId}&status={status}");
        kv.put("employId", String.valueOf(employId));
        kv.put("status", status);
        String string = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        JSONObject jsonObject = new JSONObject(string);
        int code = jsonObject.getInt("code");
        List<Order> newList = new ArrayList<Order>();
        if (code == 0) {
            JSONArray data = jsonObject.getJSONArray("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            newList = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
            }.getType());
        }
        return newList;
    }

    @Override
    public Long countNotPayByPassenger(Long passengerId) {
        Long notPayAmounts = 0L;

        try {
            StringBuilder builder = new StringBuilder();
            builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.COUNT_NOTPAY_BY_PASSENGER).append("?appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();
            builder.append("&passengerId={passengerId}");
            kv.put("passengerId", String.valueOf(passengerId));
            String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    Long data = jo.getLong("data");
                    notPayAmounts = data;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return notPayAmounts;
    }

    @Override
    public Result<Order> updateRealMoney(Order order, BigDecimal couponMoney, BigDecimal cashMoney,
                                         BigDecimal signMoney, BigDecimal balanceMoney, BigDecimal alipayMoney, BigDecimal weixinMoney,
                                         BigDecimal driverMoney, BigDecimal memberMoney, BigDecimal wxMoney, String content) {
        Result<Order> result = new Result<Order>();
        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        String operator = principal.getUsername();
        if (null == couponMoney) {
            couponMoney = BigDecimal.ZERO;
        }
        if (null == cashMoney) {
            cashMoney = BigDecimal.ZERO;
        }
        if (null == signMoney) {
            signMoney = BigDecimal.ZERO;
        }
        if (null == balanceMoney) {
            balanceMoney = BigDecimal.ZERO;
        }
        if (null == alipayMoney) {
            alipayMoney = BigDecimal.ZERO;
        }
        if (null == weixinMoney) {
            weixinMoney = BigDecimal.ZERO;
        }

        final BigDecimal newCash = couponMoney.add(cashMoney).add(signMoney).add(balanceMoney).add(alipayMoney).add(weixinMoney);

        StringBuilder sb = new StringBuilder();
        sb.append(zhuanxianApi.getZhuanxianBaseURL());
        sb.append(ZhuanxianApi.UPDATE_REALMONEY);

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("orderId", String.valueOf(order.getId()));
        kv.add("couponMoney", String.valueOf(couponMoney));
        kv.add("cashMoney", String.valueOf(newCash));
        kv.add("signMoney", String.valueOf(signMoney));
        kv.add("balanceMoney", String.valueOf(balanceMoney));
        kv.add("alipayMoney", String.valueOf(alipayMoney));
        kv.add("weixinMoney", String.valueOf(weixinMoney));
        kv.add("operator", operator);
        kv.add("content", content);

        zhuanxianApi.postMultiValueMap(sb.toString(), kv, settingUtils.get());

        Driver driver = driverMapper.selectByPrimaryKey(order.getEmployId());

        if (driverMoney.compareTo(BigDecimal.ZERO) != 0) {
            driver.setVirtual(driver.getVirtual().add(driverMoney));
            driverMapper.updateVirtualByPrimaryKey(driver.getVirtual(), driver.getId());

            DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
            driverPaymentsRecord.setMoney(driverMoney);
            driverPaymentsRecord.setAfterMoney(driver.getVirtual());
            driverPaymentsRecord.setDriverId(driver.getId());
            driverPaymentsRecord.setDriverRealName(driver.getRealname());
            driverPaymentsRecord.setDriverUserName(driver.getUsername());
            driverPaymentsRecord.setDriverPhone(driver.getPhone());
            driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
            driverPaymentsRecord.setOrderId(order.getId());
            driverPaymentsRecord.setOrderNumber(order.getOrderNo());
            driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_ZHUANXIAN);
            driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
            driverPaymentsRecord.setMemo("【" + principal.getUsername() + "】将订单金额由￥" + order.getRealPay() + "修改为￥" + newCash + "，原因：" + content + "，订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】");
            driverPaymentsRecord.setOperating(principal.getUsername());
            if (driverMoney.doubleValue() > 0) {
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_MODIFY);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
            } else {
                driverPaymentsRecord.setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_MODIFY);
                driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
            }
            driverPaymentsRecord.setHappend(new Date());
            driverPaymentsRecordMapper.insertRecord(driverPaymentsRecord);

        }
        if (memberMoney.compareTo(BigDecimal.ZERO) != 0) {
            Result<Passenger> result_p = passengerApi.findOnePassenger(order.getPassengerId(), settingUtils.get());
            Passenger passenger = result_p.getResult();

            if (null != passenger) {

                String memo = "【" + principal.getUsername() + "】将订单金额由￥" + order.getRealPay() + "修改为￥" + newCash + "，原因：" + content + "，订单号【<a target='_blank' href='/zhuanxian/detail/" + order.getId() + "'>" + order.getOrderNo() + "</a>】";

                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    passengerApi.createPassengerAccount(passenger, null, memberMoney, PassengerAccount.PayType.CASH_MODIFY, principal.getUsername(), memo, order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_ZHUANXIAN, null, true, false, settingUtils.get());
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = passengerApi.findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get()).getResult();
                    if (null != enterprise) {
                        passengerApi.createEnterpriseAccount(enterprise, memberMoney, PassengerAccount.PayType.CASH_MODIFY, principal.getUsername(), memo, order.getId(), order.getOrderNo(), PassengerAccount.ORDER_TYPE_ZHUANXIAN, null, true, false, settingUtils.get());
                    }
                }

            }
        }
        BigDecimal financialCash = driverMoney.multiply(new BigDecimal(-1));

        FinancialRecord financialRecord = financialRecordMapper.selectByOrderIdAndOrderType(order.getId(), FinancialRecord.FINANCIALRECORD_TYPE_SHOURU, FinancialRecord.ORDER_TYPE_ZHUANXIAN);
        if (null != financialRecord) {
            BigDecimal oldMoney = financialRecord.getMoney();
            financialRecord.setMoney(financialRecord.getMoney().add(financialCash));
            financialRecord.setMemo(financialRecord.getMemo() + " ; " + "<br/>【" + principal.getUsername() + "】将订单金额由￥" + order.getRealPay() + "修改为￥" + newCash + "，原因：" + content + "，修改前￥" + oldMoney + "，修改后￥" + financialRecord.getMoney() + "");
            financialRecordMapper.updateByPrimaryKey(financialRecord);
        }
        final String clientPhone = order.getPassengerPhone();
        final String orderNumber = order.getOrderNo();
        final Long companyId = order.getCompanyId();
        Company orderCompany = companyMapper.selectByPrimaryKey(companyId);
        Company mainCompany = companyMapper.selectMainCompany();
        Setting setting = settingUtils.get();
        if (!mainCompany.getId().equals(orderCompany.getId()) && setting.isSmsMainCompany()) {
            orderCompany = mainCompany;
        }
        final Company finalCompany = orderCompany;

        try {
            SmsTemplet templet = smsService.findByAlias(finalCompany.getId(), SmsType.modifyZhuanxianCash);

            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                smsService.sendSms(clientPhone, "modifyZhuanxianCash", "{\"订单号\":\"" + "***" + orderNumber.substring(8) + "\",\"收费金额\":\"" + newCash + "" + "\",\"投诉建议电话\":\"" + finalCompany.getTelephone() + "\"}", finalCompany.getId(), 0, finalCompany.getSignName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        result.setSuccess(true);

        result.setMessage("修改金额成功");
        return result;
    }

    @Override
    public OrderOrbit findOrbitByOrderId(Long id) {
        OrderOrbit orderOrbit = new OrderOrbit();
        try {

            StringBuilder builder = new StringBuilder();
            builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_ORDERORBIT).append("?orderId={orderId}&appKey={appKey}");
            Map<String, String> kv = new HashMap<String, String>();
            kv.put("orderId", String.valueOf(id));
            String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
            if (null != result) {
                JSONObject jo = new JSONObject(result);
                Integer code = jo.getInt("code");
                if (code == 0) {
                    JSONObject data = jo.getJSONObject("data");
                    Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                    orderOrbit = gson.fromJson(data.toString(), OrderOrbit.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderOrbit;
    }

    @Override
    public List<Order> queryRunOrderByEmploy(Long driverId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_EMPLOY_RUNORDER).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("employId", String.valueOf(driverId));
        builder.append("&employId={employId}");
        List<Order> list = new ArrayList<Order>();
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }

        return list;

    }

    @Override
    public List<Order> findRunOrderByLineId(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_RUN_ORDER_LINE).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("lineId", String.valueOf(id));
        builder.append("&lineId={lineId}");
        List<Order> list = new ArrayList<Order>();
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }

        return list;
    }

    @Override
    public List<Order> queryRunOrderByCar(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_RUN_ORDER_CAR).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("carId", String.valueOf(id));
        builder.append("&carId={carId}");
        List<Order> list = new ArrayList<Order>();
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }

        return list;
    }

    @Override
    public Page<Order> findByDriverAndFinishTime(Long employId, Date start,
                                                 Date end, Integer page, Integer limit) {

        Pageable pageable = new PageRequest(page, limit);

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_FINISHED_BY_EMPLOY).append("?appKey={appKey}&page={page}&rows={rows}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(page + 1));
        kv.put("rows", String.valueOf(limit));

        kv.put("employId", String.valueOf(employId));
        builder.append("&employId={employId}");

        if (null != start) {
            kv.put("start", String.valueOf(start.getTime()));
            builder.append("&start={start}");
        }
        if (null != end) {
            kv.put("end", String.valueOf(end.getTime()));
            builder.append("&end={end}");
        }

        List<Order> list = new ArrayList<Order>();
        long total = 0;
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return new PageImpl<Order>(list, pageable, total);
    }

    @Override
    public Long countActivedOrdersByDriver(Long driverId) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_BY_EMPLOY).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("employId", String.valueOf(driverId));
        builder.append("&employId={employId}");

        List<Order> list = new ArrayList<Order>();
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray ja = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return (long) list.size();
    }

    @Override
    public Rate findRateOne(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_ORDEREVIEW_ONE).append("?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        OrderReview or = null;
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                or = gson.fromJson(data.toString(), new TypeToken<OrderReview>() {
                }.getType());
            }
        }
        Rate r = null;
        if (or != null) {
            r = new Rate();
            r.setContent(or.getContent());
            r.setCreated(or.getCreated());
            r.setDriverId(or.getEmployId());
            r.setDriverName(or.getEmployName());
            r.setId(or.getId());
            r.setManager(false);
            r.setMemberId(or.getPassengerId());
            r.setMemberName(or.getPassengerName());
            r.setOrderId(or.getOrderId());
            r.setOrderNumber(or.getOrderNo());
            r.setStarLevel(or.getScore().floatValue());
            r.setUpdated(or.getUpdated());
        }
        return r;
    }

    @Override
    public void deleteRateOne(Long id) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.DELETE_ORDEREVIEW).append("?appKey={appKey}");
        Map<String, String> kv = new LinkedHashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        String result = zhuanxianApi.post(builder.toString(), kv, settingUtils.get());
        if (null != result) {
        }
    }

    @Override
    public List<Order> findByStatus(Integer orderStatusPaidan) {
        List<Order> list = new ArrayList<Order>();

        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.QUERY_ORDER).append("?appKey={appKey}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("allstatus", String.valueOf(orderStatusPaidan));
        builder.append("&allstatus={allstatus}");
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                ;
                list = gson.fromJson(ja.toString(), new TypeToken<List<Order>>() {
                }.getType());
            }
        }
        return list;

    }

    @Override
    public Long countFinishedByPassengerAndFinishTime(Long id,
                                                      String orderFromSource, Date startDate, Date endDate) {
        return zhuanxianApi.countFinishedByPassengerAndFinishTime(id, orderFromSource, startDate, endDate, settingUtils.get());
    }

    @Override
    public PageVo<DriverOrderDetailVo> driverOrderDetailCount(Long driverId, Date start, Date end) {
        StringBuilder builder = new StringBuilder();
        builder.append(zhuanxianApi.getZhuanxianBaseURL()).append(ZhuanxianApi.DRIVERORDERDETAILCOUNT).append(".json?appKey={appKey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (driverId != null) {
            kv.put("driverId", driverId + "");
            builder.append("&driverId={driverId}");
        }
        if (start != null) {
            kv.put("startDate", start.getTime() + "");
            builder.append("&startDate={startDate}");
        }
        if (end != null) {
            kv.put("endDate", end.getTime() + "");
            builder.append("&endDate={endDate}");
        }
        String result = zhuanxianApi.get(builder.toString(), kv, settingUtils.get());
        PageVo<DriverOrderDetailVo> page = new PageVo<DriverOrderDetailVo>();

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                Long couont = jo.optLong("data", 0L);
                page.setTotalElements(couont);
            }
        }

        return page;
    }

    @Override
    public long countRunOrderByPassenger(Long passengerId) {
        return zhuanxianApi.countRunOrderByPassenger(passengerId, settingUtils.get());
    }

}
